I am learning how to work with files in C. So far I can write (create) txt files using fopen + fprintf function, but I did not understand how the read and write parameter works.
Whenever I use a+, w+ or r+, my program only writes the information, but does not read it. I have to close the file and reopen it in read only mode. The following code explains better:
This code does not work for me:
#include<stdio.h>
#include<stdlib.h>
int main(void){
FILE * myfile = nullptr;
myfile = fopen("./program.txt", "a+"); // I also tried w+ and r+
int num1 = 4;
int num2 = 0;
fprintf(myfile, "%d", num1);
fscanf(myfile, "%d", &num2); // the atribution does not occur
// num2 keeps previous value
printf("%d", num2);
fclose(myfile);
return (0);}
This works fine:
#include<stdio.h>
#include<stdlib.h>
int main(void){
FILE * myfile = nullptr;
myfile = fopen("./program.txt", "w");
int num1 = 4;
int num2 = 0;
fprintf(myfile, "%d", num1);
fclose(myfile); //close the file!
myfile = fopen("./program.txt", "r"); // reopen as read only!
fscanf(myfile, "%d", &num2);
printf("%d", num2);
fclose(myfile);
return (0);}
Is there any way to work with a file (read and modify it) without need to close it each time?