本文實現一個完整的文件字符統計程序:讀取同目錄下 1.txt,統計用戶輸入字符(英文字母/標點)出現次數與佔比。涵蓋文件讀取、字符處理、錯誤處理、界面交互全流程。
1.txt
#include <stdio.h>
#include <windows.h> // system(), Sleep() 等
#include <string.h>
#include <conio.h> // getch()
int main() {
FILE *fp;
double total = 0, target_count = 0;
char ch, target;
// 界面設置
system("color a"); // 綠色背景
printf("\n\t統計 1.txt 中指定字符出現次數\n");
printf("\t僅支持單個英文字母/標點,不支持漢字\n");
printf("\t按任意鍵繼續..."); getch();
// 輸入目標字符
printf("\n請輸入要查詢的字符:");
scanf(" %c", &target); // 空格跳過換行符
// 統計總字符數(這裡簡化為統計 '/' 數量作為演示基準)
if ((fp = fopen("1.txt", "r")) == NULL) {
perror("無法打開文件");
return 1;
}
while ((ch = fgetc(fp)) != EOF) {
if (ch == '/') total++; // 原程序邏輯:以 '/' 為基準
}
fclose(fp);
// 統計目標字符
if ((fp = fopen("1.txt", "r")) == NULL) return 1;
while ((ch = fgetc(fp)) != EOF) {
if (ch == target) target_count++;
}
fclose(fp);
// 輸出結果
printf("\n\t'/' 出現 %.0f 次", total);
printf("\n\t'%c' 出現 %.0f 次", target, target_count);
if (total > 0)
printf("\n\t'%c' 佔比: %.2f%%", target, 100 * target_count / total);
printf("\n\n按任意鍵退出..."); getch();
return 0;
}
| 函數/技術 | 說明 |
|---|---|
| fopen("1.txt", "r") | 只讀模式打開文本文件,返回 FILE* |
| fgetc(fp) | 讀取單字符,返回 int(含 EOF),非 char |
| EOF | 文件結束標誌,通常為 -1 |
| fclose(fp) | 關閉文件,刷新緩衝區,釋放資源 |
| perror() | 打印系統錯誤信息(含 errno 文本) |
| scanf(" %c", &c) | 前置空格跳過殘留換行符/空白 |
| system("color a") | Windows 控制台顏色設置(a=亮綠) |
| getch() | 無回顯讀單字符,暫停程序 |
#include <stdio.h>
#include <stdlib.h>
#define MAX_CHAR 256
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "用法: %s <文件名>\n", argv[0]);
return 1;
}
FILE *fp = fopen(argv[1], "r");
if (!fp) { perror("打開失敗"); return 1; }
long freq[MAX_CHAR] = {0};
int ch, total = 0;
while ((ch = fgetc(fp)) != EOF) {
if (ch >= 0 && ch < MAX_CHAR) {
freq[ch]++;
total++;
}
}
fclose(fp);
printf("文件: %s, 總字符: %d\n", argv[1], total);
printf("字符頻率統計 (僅顯示出現>0):\n");
for (int i = 0; i < MAX_CHAR; i++) {
if (freq[i] > 0) {
char display = (i >= 32 && i <= 126) ? i : '.';
printf(" '%c' (0x%02X): %5ld %.2f%%\n",
display, i, freq[i], 100.0 * freq[i] / total);
}
}
return 0;
}
wchar_t + fgetwc 處理fgetc 有函數調用開銷。大文件用 fread 批量讀取緩衝區處理fopen 必須配對 fclose,錯誤路徑亦然
// 統計行數
int lines = 0;
while ((ch = fgetc(fp)) != EOF) if (ch == '\n') lines++;
// 統計單詞(簡易版:空白分隔)
int in_word = 0, words = 0;
while ((ch = fgetc(fp)) != EOF) {
if (ch == ' ' || ch == '\n' || ch == '\t') in_word = 0;
else if (!in_word) { in_word = 1; words++; }
}
文件字符統計是 C 語言文件 I/O 的入門實戰。核心模式:fopen → 循環 fgetc/fread → 處理 → fclose。生產代碼要注意:錯誤檢查、編碼兼容、大文件性能、資源管理。掌握這套模式,即可處理日誌分析、數據清洗、協議解析等大量實際場景。