I am new to C language and i just started working with files. 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. The string s is empty. 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 ). Note that you are flushing stdin
, which does not make sense here (and if it ever makes sense, I'm not sure).
So a call like
fseek(f,0,SEEK_SET)
before your first fgets
should solve the problem.
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.