如何在C中正确使用fscanf函数?

问题描述 投票:0回答:1

我正在学习如何使用C中的文件。到目前为止,我可以使用fopen + fprintf函数编写(创建)txt文件,但我不明白读取和写入参数的工作原理。

每当我使用+,w +或r +时,我的程序只会写入信息,但不会读取它。我必须关闭文件并以只读模式重新打开它。以下代码更好地解释:

此代码对我不起作用:

#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);}

这很好用:

#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);}

有没有办法处理文件(读取和修改它)而不需要每次都关闭它?

c file scanf
1个回答
3
投票

当您想要回读刚才写的内容时,必须将文件光标移回到开头(或者您想要开始阅读的任何位置)。这是用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

© www.soinside.com 2019 - 2024. All rights reserved.