简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM