相較於字元級 fgetc/fputc 與格式化 fscanf/fprintf,fgets/fputs 以行為單位處理文字檔,適合逐行讀取、記錄日誌、配置檔解析。
char *fgets(char *str, int n, FILE *stream);
n-1 個字元,遇到 \n、EOF 或滿 n-1 停止。\n 會被保留 在緩衝區末尾 (後接 \0)。str,失敗/EOF 回傳 NULL。
#include
#include
int main(void)
{
FILE *fp;
char str[11]; /* 容納 10 字元 + \0 */
if ((fp = fopen("e10_1.c", "rt")) == NULL) {
printf("Cannot open file strike any key exit!");
getch();
return 1;
}
fgets(str, 11, fp); /* 讀最多 10 字元 */
printf("%s", str); /* 直接輸出,含換行 */
fclose(fp);
getch();
return 0;
}
int fputs(const char *str, FILE *stream);
puts 不同)。EOF。
#include
#include
int main(void)
{
FILE *fp;
char ch, st[20];
if ((fp = fopen("string", "at+")) == NULL) {
printf("Cannot open file strike any key exit!");
getch();
return 1;
}
printf("input a string:\n");
scanf("%19s", st); /* 限制長度防溢位 */
fputs(st, fp); /* 寫入檔案末尾 */
rewind(fp); /* 移回檔案開頭 */
ch = fgetc(fp);
while (ch != EOF) {
putchar(ch);
ch = fgetc(fp);
}
printf("\n");
fclose(fp);
getch();
return 0;
}
| 特性 | fgets | fputs | gets/puts (標準 I/O) |
|---|---|---|---|
| 自動加 \n | 保留輸入的 \n | 不加 | gets 丟棄 \n,puts 自動加 \n |
| 緩衝區溢位保護 | 有 (n-1 限制) | N/A (僅寫入) | gets 無保護 (極危險,C11 已移除) |
| 檔案指標 | 需 FILE* | 需 FILE* | stdin/stdout |
| 二進位檔適用 | 是 (但會在 \0 停止) | 是 | 否 |
str[strcspn(str, "\n")] = '\0';。while (fgets(buf, sizeof buf, fp)) 是標準逐行讀取慣用語。\r\n 轉為 \n,影響 ftell 位置計算;二進位模式 "rb"/"wb" 保持原貌。fscanf 讀取異常;若需混用,中間插 fgetc 吃掉換行或改用 fgets + sscanf。fgets 記憶體占用固定 (緩衝區大小),適合串流處理超大日誌檔。std::getline(std::ifstream, std::string) 自動管理記憶體、無長度限制。getline(&buf, &len, fp) 自動擴充緩衝區 (C 標準庫擴展)。fgets_s 邊界檢查版本 (MSVC 支援)。