在使用 read() 系統調用逐字節讀取文本文件進行字符統計時,若直接將讀取結果存入 int 變量並與字符字面量(如 ' '、'\t'、'\n')比較,會導致判斷失效。根本原因在於 read() 僅向內存寫入 1 字節,而 int 佔用 4 字節,高位 3 字節殘留垃圾數據,參與比較導致永不相等。
int c;
int ret;
while ((ret = read(fd, &c, 1)) != 0) {
if (c == ' ') { ... } // 永遠不會成立
else if (c == '\t') { ... }
}
輸出調試信息可見 c 的十六進制值高位非零(如 0xXXYYZZ20),而 ' ' 僅為 0x20。
int c = 0; 確保高位清零,後續每次 read 只覆蓋低位。if ((char)c == ' ') 或 if (c == (int)' '),僅比較低 8 位。建議養成「定義即初始化」的習慣,避免未初始化變量導致的難以排查的邏輯錯誤。
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
int main(int argc, char **argv) {
int fd;
long nc = 0, lc = 0, tc = 0;
int c = 0; // 關鍵:初始化為 0
int ret;
fd = open(argv[1], O_RDONLY);
while ((ret = read(fd, &c, 1)) != 0) {
nc++;
if ((char)c == ' ') lc++; // 也可寫作 if (c == ' ') 因已初始化
else if ((char)c == '\t') tc++;
}
printf("char count: %ld\n", nc);
printf("space count: %ld\n", lc);
printf("tab count: %ld\n", tc);
close(fd);
return 0;
}