I need to write some code to read an equation from a text file and write the answer to a new one, and I'm completely stuck
I've managed to read the question and print it in terminal as characters, but that's it.
this new code can't even do that.
for those asking, the exact wording of the question is this:
"Read an input file: questions.txt; and produce a program that creates an output file answers.txt that includes
the question and the answer for each line in the questions file.
For example, if the line in questions is:
5*5
the answer file should read:
5*5 = 25
Allow for the following operations: +, -, *, /, % and for the correct order of operations. Also allow for at least 2
operators (3 operands), for example:
3+5*5 = 28"
My main problem is reading the equation from the text file and separating it into numbers and the operator symbol
FILE *fp;
int a, b, c, ch, i, number[100];
char input[5];
fp = fopen ("questions.txt", "r");
while(1)
{
ch = fgetc(fp);
if (ch == EOF)
{
break;
}
else
{
input[i] = ch;
}
}
fclose(fp);
printf("%s", input);
}
There are errors:
check file has been open correcly: if (fp != NULL)
i = 0; on begin, now we dont know value
input[i] = ch; => input[i++] = (char)ch;
if (ch == EOF) => if (ch == EOF && i < 4) 4 because 5 - 1 and move this to const or macro
After break of while input[i] = '\0';
You need to open the file you want to read from in read mode with the normal fopen('questions.txt', 'r') like you did. Next, you need to fopen('newFile.txt', 'w') you want to write to in w write mode. Use a while loop to get each character of the questions.txt file with getc(fileToRead) while you haven''t hit the end of the questions.txt file, hence ... != EOF, and write to the newFile.txt. The printf("%c", c) is to print each character as you read it from questions.txt.
FILE *fileToRead, *fileToWrite;
int c;
//open the questions.txt file in read mode
*fileToRead = fopen ("questions.txt", "r");
//create newFile.txt and open it in write mode
*fileToWrite = fopen ("newFile.txt", "w");
while ((c = getc(fileToRead)) != EOF) {
putc((char)c, fileToWrite );
printf("%c", (char)c);
}
fclose(fileToRead);
fclose(fileToWrite);
Related
I'm new to C language and I'm trying to save data to a .csv and read the same data in a very simple program.
char c;
FILE *fp;
fp = fopen("file.csv", "w+");
fprintf(fp, "Hello;World\nLine");
fclose(fp);
fp = fopen("file.csv", "r");
while (getc(fp) != EOF) {
printf("%c", getc(fp));
}
fclose(fp);
I don't know why the output is wrong:
el;ol
ie
Thanks in advance
Because you are reading a character in the loop condition (so it prints out every other one when printing), and reading another one when printing it out. Try this:
int ch;
while ((ch=getc(fp)) != EOF) {
printf("%c", ch);
}
Here:
while (getc(fp) != EOF) {
printf("%c", getc(fp));
}
You are calling getc() twice every time through the loop, but only printing one character. So you get half te hrces rm te fl n ls h ohr hl.
I am having two inputs :video1.y and video2.y .I want to Concatenate these two files to create one video.y file ??I am writing code in C .It may be basic question but not able to do that !! Both inputs are having same hight and width .
Code:
int main()
{
// Open two files to be merged
FILE *fp1 = fopen("D:\\dump\\video1.y", "rb");
FILE *fp2 = fopen("D:\\dump\\video2.y", "rb");
// Open file to store the result
FILE *fp3 = fopen("D:\\dump\\video.y", "wb");
char c; //Change char to int as per answer given by user3710044..
//...Which is working !!
if (fp1 == NULL || fp2 == NULL || fp3 == NULL)
{
puts("Could not open files");
exit(0);
}
// Copy contents of first file to video3.y
while ((c = fgetc(fp1)) != EOF)
fputc(c, fp3);
// Copy contents of second file to video3.y
while ((c = fgetc(fp2)) != EOF)
fputc(c, fp3);
printf("Merged video1.y and video2.y into video.y");
fclose(fp1);
fclose(fp2);
fclose(fp3);
return 0;
}
video1.y and video2.y are of 55 MB .and my output is 3 KB.I am not able to concatenate this two inputs
The type of the c variable is a char this cannot hold the value for EOF and all 256 byte values.
As it happens on your machine char is a signed type so the cast return result from fgetc and the cast value of EOF actually mean that an EOF is found at the end of a file. The problem is that if the file contains an 0xFF byte this is also seen as an EOF.
In summary, change the type of c to an int.
I am sorry the question was not very clear and the code i have so far is shown below and i am just stuck on how i can use the while loop to print the contents of the file.
#include<stdio.h>
int main()
{
FILE *number;
/* Open the file 'numbers' for reading */
number = fopen("numbers.dat", "r");
if (number != NULL) {
/* A bit of space for a line of text */
char lineOfText[100];
while (fgetc(lineOfText, 100, number) != NULL) {
printf("%s\n", lineOfText);
}
fclose(number);
}
/* sorry, my question was not clear and to clarify i am trying to
Print out the contents of the file with one entry per line, my .dat file includes
1,2,3,4,5,6,7,8,9 and i am trying to print them out in this format
1
2
3
4 and so on...
*/
To start you off...
FILE * f;
int c;
f=fopen ("numbers.txt","r");
while((c = fgetc(f)) != EOF) printf("%c", isdigit(c)? c : ' ');
fclose (f);
Hi I have recently been given a task in C.
The aim of the task is to read from two text files and output each line of each file side by side with a separator string in the middle of said lines.
Example:
file 1 contains:
green
blue
red
file 2 contains:
rain
sun
separator string = xx
output =
greenxxrain
bluexxsun
redxx
I have managed to do this but was wondering if anyone else has any alternatives. Here is my code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int f1, f2;
FILE *file1, *file2;
file1 = fopen("textone", "r"); //open file1 for reading.
file2 = fopen("texttwo", "r"); //open file2 for reading.
//if there are two files ready, proceed.
if (file1 && file2){
do{
//read file1 until end of line or end of file is reached.
while ((f1 = getc(file1)) != '\n' && f1!= EOF ){
//write character.
putchar(f1);
}
//print separator string.
printf("xx");
//read file2 until end of line or end of file is reached.
while ((f2 = getc(file2)) != '\n' && f2!= EOF ){
//write character.
putchar(f2);
}
putchar('\n');
//do this until both files have reached their end.
}while(f1 != EOF || f2 != EOF);
}
}
You might find fgets(3) useful. It can be used to read a whole line at once. That said, it has downsides, too - you need to know how long the line is going to be, for example, or at least handle the case where the line is longer than your buffer. Your implementation seems fine to me (except that you should call fclose(3)).
You could write a simple function to avoid the 'big' repetition in the do { ... } while loop:
static void read_and_echo_line(FILE *fp)
{
int c;
while ((c = getc(fp)) != EOF && c != '\n')
putchar(c);
}
...
do
{
read_and_echo_line(file1);
printf("xx");
read_and_echo_line(file2);
putchar('\n');
} while (!feof(file1) || !feof(file2));
In this context, it is fairly reasonable to use feof() as shown (though it is not a function to use most of the time). Alternatively:
static int read_and_echo_line(FILE *fp)
{
int c;
while ((c = getc(fp)) != EOF && c != '\n')
putchar(c);
return(c);
}
...
do
{
f1 = read_and_echo_line(file1);
printf("xx");
f2 = read_and_echo_line(file2);
putchar('\n');
} while (f1 != EOF || f2 != EOF);
I use below code to read a char from file and replace it with another,
but I have an error.loop in going to end of file.
What is wrong?
I tested this code on linux (netbeans IDE) and it was correct and worked beautiful but when I tried to use VS 2008 in windows , I found a non end loop.
//address = test.txt
FILE *fp;
fp=fopen(address,"r+");
if(fp == 0)
{
printf("can not find!!");
}
else
{
char w = '0'; /// EDIT : int w;
while(1)
{
if((w = fgetc(fp)) != EOF)
{
if((w = fgetc(fp)) != EOF)
{
fseek(fp,-2,SEEK_CUR);
fprintf(fp,"0");
}
}
else
{
break;
}
}
}
fclose(fp);
You are storing the result of fgetc in a char, instead of an int.
char w = '0'; /* Wrong, should be int. */
Incidentally, this problem is mentioned in the C FAQ.
If type char is unsigned, an actual
EOF value will be truncated (by having
its higher-order bits discarded,
probably resulting in 255 or 0xff) and
will not be recognized as EOF,
resulting in effectively infinite
input.
EDIT
Reading your question again, it's highly fishy the way you seek back two characters and write one character. That could well lead to an infinite loop.
EDIT2
You (likely) want something like this (untested):
while ((w = getc(fp)) != EOF) {
fseek(fp, -1, SEEK_CUR);
fprintf(fp, "0");
fflush(fp); /* Apparently necessary, see the answer of David Grayson. */
}
The fopen documentation on cplusplus.com says:
For the modes where both read and
writing (or appending) are allowed
(those which include a "+" sign), the
stream should be flushed (fflush) or
repositioned (fseek, fsetpos, rewind)
between either a reading operation
followed by a writing operation or a
writing operation followed by a
reading operation.
We can add an fflush call after the fprintf to satisfy that requirement.
Here is my working code. It creates a file named example.txt and after the program exits that file's contents will be 000000000000n.
#include <stdio.h>
int main(int argc, char **argv)
{
FILE * fp;
int w;
fp = fopen("example.txt","w");
fprintf(fp, "David Grayson");
fclose(fp);
fp = fopen("example.txt","r+");
while(1)
{
if((w = fgetc(fp)) != EOF)
{
if((w = fgetc(fp)) != EOF)
{
fseek(fp,-2,SEEK_CUR);
fprintf(fp,"0");
fflush(fp); // Necessary!
}
}
else
{
break;
}
}
fclose(fp);
}
This was tested with MinGW in Windows.