0
#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 someone teach me what's wrong with my code? Below is my test, but I didn't get what I expected:

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

My assumption is that this is a problem of character encoding, but when I use fgets to read the text from an existing file, it works fine. All my files (and code) are written in Emacs, I don't know what causes this garbled output

Kyuvi
  • 360
  • 3
  • 13
tian tong
  • 793
  • 3
  • 10
  • 21

1 Answers1

2

fp is at the end after you write. Move it to initial position before using fseek reading again:

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

Other option is to fclose it and fopen it again. It depends on what you want to do.

P.P
  • 117,907
  • 20
  • 175
  • 238