首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C >> 關於C

C 標準庫 核心函式速查:流操作、檔案 I/O、區塊讀寫與定位

     編輯:關於C

字元級標準 I/O

函式原型說明
getcharint getchar(void)從 stdin 讀一字元,EOF 為 -1
putcharint putchar(int c)向 stdout 寫一字元

流操作(通用 FILE*)

函式原型說明
getcint getc(FILE *stream)讀一字元,可用於任意流
putcint putc(int c, FILE *stream)寫一字元
fgetcint fgetc(FILE *stream)getc 函式版本(非巨集)
fputcint fputc(int c, FILE *stream)putc 函式版本

檔案開啟模式

模式含義檔案需存在
"r"唯讀是
"w"唯寫,截斷/建立否
"r+"讀寫,不截斷是
"w+"讀寫,截斷/建立否
"a"附加寫入否
"a+"讀寫附加否

二進位模式:在模式字串加 b(如 "rb"),Windows 必加,Linux 忽略亦可。

檔案關閉

int fclose(FILE *stream); // 成功 0,失敗 EOF

完整範例:鍵盤輸入存檔並回讀顯示

#include <stdio.h>
int main(void) {
    FILE *fp = fopen("myFile.txt", "w+");
    if (!fp) return 1;
    int ch;
    while ((ch = getchar()) != '#') fputc(ch, fp);
    fclose(fp);

    fp = fopen("myFile.txt", "r");
    if (!fp) return 1;
    while ((ch = fgetc(fp)) != EOF) putchar(ch);
    fclose(fp);
    return 0;
}

區塊 I/O:fread / fwrite

size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);
  • size * nmemb = 總位元組數。
  • 返回實際讀寫項目數(非位元組數)。
  • 常用技巧:size=1, nmemb=bufsize,返回值即位元組數。

檔案定位:fseek / ftell / rewind

int fseek(FILE *stream, long offset, int whence);
// whence: SEEK_SET(開頭) SEEK_CUR(目前) SEEK_END(結尾)
long ftell(FILE *stream);        // 目前位置
void rewind(FILE *stream);       // 回到開頭

範例:修改檔案第 5 位元組為小寫

FILE *fp = fopen("test.txt", "r+b");
fseek(fp, 5, SEEK_SET);
fputc('i', fp);   // 將第 6 個字元(索引 5)改為 'i'
fclose(fp);

常見錯誤提醒

  • 文字模式開啟二進位檔導致換行符轉換(Windows)。
  • fseek 在文字模式下僅支援 SEEK_SET 且 offset 必須為 ftell 返回值。
  • 忘記檢查 fopen 返回 NULL。
  • 緩衝區未刷新就關閉檔案(正常 fclose 會自動刷新)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved