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 的危險所以可以使用puts和fputs的不同是puts會在輸出的最後加上一個\n而fputs不會