user10906383
user10906383

Reputation: 323

How do I correctly use fscanf function in C?

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?

Upvotes: 0

Views: 821

Answers (1)

Henri Menke
Henri Menke

Reputation: 10939

When you want to read back in what you just wrote, you have to move the file cursor back to the start (or whatever position you want to start reading at). That is done with fseek.

#include<stdio.h>
#include<stdlib.h>

int main(void) {
    FILE * myfile = NULL;

    myfile = fopen("./program.txt", "a+"); // I also tried w+ and r+

    int num1 = 4;
    int num2 = 0;

    fprintf(myfile, "%d", num1);
    fseek(myfile, 0, SEEK_SET);
    fscanf(myfile, "%d", &num2);  // the atribution does not occur
                                  // num2 keeps previous value
    printf("%d", num2);
    fclose(myfile);
}

Live example on Wandbox

Upvotes: 3

Related Questions