tian tong
tian tong

Reputation: 833

Getting garbled output 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 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

Upvotes: 0

Views: 252

Answers (1)

P.P
P.P

Reputation: 121387

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.

Upvotes: 2

Related Questions