我有一个带有cmd命令转发输出的文件。一个C程序循环遍历字符,直到它到达文件的末尾。但不幸的是,在文件实际结束之前,文件中有一些EOF指示符。 该文件的内容是:
Abbildname PID Sitzungsname Sitz.-Nr. Speichernutzung
========================= ======== ================ =========== ===============
System Idle Process 0 Services 0 8 K
System 4 Services 0 5ÿ744 K
smss.exe 440 Services 0 276 K
csrss.exe 616 Services 0 1ÿ924 K
wininit.exe 720 Services 0 944 K
services.exe 792 Services 0 7ÿ892 K
lsass.exe 800 Services 0 14ÿ300 K
svchost.exe 924 Services 0 420 K
fontdrvhost.exe 952 Services 0 680 K
svchost.exe 960 Services 0 23ÿ880 K
WUDFHost.exe 1012 Services 0 7ÿ416 K
svchost.exe 484 Services 0 14ÿ816 K
svchost.exe 544 Services 0 5ÿ196 K
这就是我如何阅读文件的内容:
FILE *file;
file = fopen(completePath, "r");
char character;
while((character=getc(file))!= EOF){
putchar(character);
}
fclose(file);
任何时候有'ÿ'时都会被解释为EOF。我怎样才能解决这个问题,以便我读完整个文件并在达到实际EOF时停止?
答案 0 :(得分:5)
EOF不是char值。它是整数值。保证没有其他字符等于它。但是,在比较之前将getc返回的值(int类型)转换为char(在本例中未定义)。您应将char character;
修改为int character;
答案 1 :(得分:1)
您可以使用int feof ( FILE * stream );
检查文件结束指示符 检查是否设置了与stream关联的文件结束指示符,如果是,则返回不等于零的值。
while( (character=getc(file))!= EOF && !feof(file) )
注意:
上述代码允许character
使用char
的类型。
当character
的类型为int
时,不需要feof(file)
,因为第一个条件会正确识别EOF
。