首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

计算二进制文件的字符数解决办法

2012-03-04 
计算二进制文件的字符数本人写了一个读取文件中字符数的c程序,在unix系统下编译和运行.读txt等文件时正常,

计算二进制文件的字符数
本人写了一个读取文件中字符数的c程序,在unix系统下编译和运行.读txt等文件时正常,但是在读取二进制文件时候与要求输出不符.请大家帮我看一下问题
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int   main(){
unsigned   int   puncNum   =   0;
unsigned   int   whiteSpaceNum   =   0;
unsigned   int   otherNum   =   0;
unsigned   int   totalNum   =   0;
char   ch   =   0;
FILE   *fp   =   fopen( "valgrind.log ", "r ");

if(fp   ==   NULL){
fclose(fp);
exit(EXIT_FAILURE);
}
else   {    
while((ch   =   getc(fp))   !=   EOF)
{
if(isspace(ch))
whiteSpaceNum++;
else   if(ispunct(ch))
puncNum++;
else   otherNum++;
}
fclose(fp);
totalNum   =   whiteSpaceNum   +   puncNum   +   otherNum;
printf( "%u   punctuation   characters\n ",puncNum);
printf( "%u   whitespace   characters\n ",whiteSpaceNum);
printf( "%u   other   characters\n ",otherNum);
printf( "Total:   %u   characters\n ",totalNum);
return   EXIT_SUCCESS;
}
}

要求输出的是
8121   punctuation   characters
1494   whitespace   characters
55921   other   characters
Total:   65536   characters

我的输出是
26   punctuation   characters
5   whitespace   characters
204   other   characters
Total:   235   characters

fopen的第二个参数我试过 "r "和 "rb ",结果是一样的


[解决办法]
因为 2 进制文件中可能读取结果会出现 EOF,
所以用 while((ch = getc(fp)) != EOF) 判断可能会提前结束,
导致数目不对。

热点排行