Getting garbled from fgets() in C -


#include <stdio.h>  int main(int argc, char *argv[]) {   file *fp = fopen("sss", "w+");   char buf[100];   fputs("hello, world", fp);   fflush(fp);   fgets(buf, 100, fp);   fputs(buf, stdout);   fclose(fp);   return 0; } 

can teach me what's wrong code? test, can't expect:

% clang test.c % ./a.out ��h��%   % cat test.c hello, world% 

my assumption problem of character encoding, when use fgets read text existed file, work. files(and code) written in emacs, don't know cause garbled

fp @ end after write. move initial position before using fseek reading again:

fflush(fp); fseek(fp, 0, seek_set); fgets(buf, 100, fp); 

other option fclose , fopen again. depends on want do.


Comments