fgets, gets

Function Prototype

char *fgets(char *buf, int n, FILE *fp);
char *gets(char *buf);

fgets

  • 回傳的字串會包括 \n
  • n 個字元有包括 \0

gets

Remark

  • 回傳字串不會包括 \n
  • 因為沒有指定 buffer size,所以可能 overflow (很不安全,不要用)

Example

struct MyStruct {
	char buf[5];
	int i;
};
  • 如果我們呼叫 gets 來輸入 buf 值,則如果輸入的內容太多,可能會 overflow 造成 i 的值也改變,並且此種 bug 超難 debug 因為 error 往往是在之後調用 i 時才出現

fputs, puts

Function Prototype

char *fputs(const char *str, FILE *fp);
char *puts(const char *str);
  • puts 相較於 gets 來說不會有 overflow 的危險所以可以使用
  • putsfputs 的不同是 puts 會在輸出的最後加上一個 \nfputs 不會