简体   繁体   English

fgets 不从文件中读取字符串

[英]fgets doesnt read string from file

I am new to C language and i just started working with files.我是 C 语言的新手,刚开始处理文件。 I have a code which writes some values from an array to a file, and then i want to print everything from the file.我有一个代码将数组中的一些值写入文件,然后我想打印文件中的所有内容。 However, the fgets doesnt get anything from f.但是,fgets 没有从 f 得到任何东西。 The string s is empty.字符串 s 为空。 What am i doing wrong?我究竟做错了什么? Here is my code:这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {

    FILE *f;
    if ((f=fopen("fis.txt","r+"))==NULL) { printf ("Error\n");
        exit(1);
    }

    float *v; int n;
    char s[1000];
    scanf("%d",&n);
    v=malloc(n*sizeof(float)); int x;
    for (int i=0;i<n;i++) {
        scanf("%f",&v[i]);
        x=fprintf(f,"%f\n",v[i]);

        if (x<0) perror("Error:");
    }

    fflush(stdin);
    fgets(s,sizeof(s),f); perror("err ");//NO ERROR
    printf("%d",strlen(s));//it's 0
    printf("%s",s);//nothing
    perror("err ");//NO ERROR
    printf("\n");

    free(v);
    fclose(f);
}

You are about reading from a file to which you have previously written.您要从之前写入的文件中读取数据。 Every time when switching between reading and writing, you need to either flush the buffer or use fseek to position the file pointer properly (cf., for example, this SO answer ).每次在读取和写入之间切换时,您都需要刷新缓冲区或使用fseek正确定位文件指针(例如,参见这个 SO answer )。 Note that you are flushing stdin , which does not make sense here (and if it ever makes sense, I'm not sure).请注意,您正在刷新stdin ,这在这里没有意义(如果有意义,我不确定)。

So a call like所以一个电话就像

fseek(f,0,SEEK_SET)

before your first fgets should solve the problem.在你的第一个fgets应该解决问题之前。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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