Originally Posted by
matthayzon89
Hello,
I am working on a program (other than the attached example).
At first my FILE was declared in "r" (read) mode, then I realized that in order to write i need it to be in "w" (write) mode, but that ONLY for if I am NOT reading and writing to the same file at the same time.
So finally, I changed it to "a" (append), which is suppose to allow me to add to the data to the existing data in the input file. But it is not working, can someone please help me?
Below, is a oversimplified example of what I am trying to do, the input file contains some data such as integers for example 5 and 4. I want to read these integers from the input file and write the sum of 5+4 into the input file that I just read from so the input file that just contained "5 4" will now contain "5 4 9".
This has some problems, noted inside:
Code:
#include <stdio.h>
int main (void){
int num1, num2, sum;
FILE *ifp;
ifp = fopen("input.txt", "a");
/* When you're at the end of the file, there's no more data to be read, so these
lines do nothing */
fscanf(ifp, "%d", num1); //missing an & anyway
fscanf(ifp, "%d", num2); //ditto
/* sum wasn't set to 0, so it could be *anything* now */
sum=num1+num2;
fprintf(ifp, "%d", sum);
fclose(ifp);
return 0;
}
Here's an example with an input file with three numbers in it 30, 20 and 50, each on their own line, in the file.
Code:
#include <stdio.h>
int main (void){
char str[50];
int num1, num2, num3, sum;
FILE *ifp;
//so I can read all data in the file
ifp = fopen("input.txt", "r+w");
fscanf(ifp, "%d", &num1);
printf("\n%d", num1);
fscanf(ifp, "%d", &num2);
printf("\n%d", num2);
fscanf(ifp, "%d", &num3);
printf("\n%d", num3);
sum=0;
sum=num1+num2+num3;
//I want to append this, so I fseek() over the \n on the end of the number3 row
fseek(ifp, 0, SEEK_END);
fprintf(ifp, "%d", sum);
fclose(ifp);
ifp = fopen("input.txt", "a"); //just to show it works
rewind(ifp); //but I do need the first byte of the file
//read all data and print it
while((fgets(str, sizeof(str), ifp)) != NULL) {
printf("%s", str);
}
fclose(ifp);
printf("\n\n\t\t\t press enter when ready");
(void) getchar();
return 0;
}
Sorry for the example code being a bit clumsy, but hope it helped.