文件中的字数计数,如C中的LinuxWC命令
我正在尝试写一些类似于Linux命令wc的东西来计算任何类型文件中的字、新行和字节,我只能使用C函数read。我已经写了这段代码,我得到了换行符和字节的正确值,但是我没有得到计数单词的正确值文件中的字数计数,如C中的LinuxWC命令,c,count,word,wc,C,Count,Word,Wc,我正在尝试写一些类似于Linux命令wc的东西来计算任何类型文件中的字、新行和字节,我只能使用C函数read。我已经写了这段代码,我得到了换行符和字节的正确值,但是我没有得到计数单词的正确值 int bytes = 0; int words = 0; int newLine = 0; char buffer[1]; int file = open(myfile,O_RDONLY); if(file == -1){ printf("can not find :%s\n",myfile); }
int bytes = 0;
int words = 0;
int newLine = 0;
char buffer[1];
int file = open(myfile,O_RDONLY);
if(file == -1){
printf("can not find :%s\n",myfile);
}
else{
char last = 'c';
while(read(file,buffer,1)==1){
bytes++;
if(buffer[0]==' ' && last!=' ' && last!='\n'){
words++;
}
else if(buffer[0]=='\n'){
newLine++;
if(last!=' ' && last!='\n'){
words++;
}
}
last = buffer[0];
}
printf("%d %d %d %s\n",newLine,words,bytes,myfile);
}
使用isspace(char ch)
函数检查空白
int isInWord = 0;/*false*/
while(read(file,buffer,1)==1){
bytes++ ;
if(!isspace(buffer[0])){
isInWord = 1;/*true*/
continue;
}else{
if(buffer[0] == '\n'){
newLine++;
}else{
if(isInWord)
words++;
}
isInWord = 0;
}
}
你应该改变你的逻辑。与其寻找一个空格并增加字数,不如寻找一个非空格来增加字数。此外,与查看最后一个字符相比,使用状态变量也会有所帮助:
int main(void)
{
const char *myfile = "test.txt";
int bytes = 0;
int words = 0;
int newLine = 0;
char buffer[1];
int file = open(myfile,O_RDONLY);
enum states { WHITESPACE, WORD };
int state = WHITESPACE;
if(file == -1){
printf("can not find :%s\n",myfile);
}
else{
char last = ' ';
while (read(file,buffer,1) ==1 )
{
bytes++;
if ( buffer[0]== ' ' || buffer[0] == '\t' )
{
state = WHITESPACE;
}
else if (buffer[0]=='\n')
{
newLine++;
state = WHITESPACE;
}
else
{
if ( state == WHITESPACE )
{
words++;
}
state = WORD;
}
last = buffer[0];
}
printf("%d %d %d %s\n",newLine,words,bytes,myfile);
}
}
wc似乎有一些关于标点符号不是单词的逻辑,这段代码无法处理。与预期输出相比,您的输出是什么?您需要一个“inword”布尔值,当您阅读单词时为yes,当您不阅读单词时为no;当它变为“在一个单词中”时,您会增加单词数。定义适合自己的单词。你知道正则表达式吗?如果是,则搜索
libpcre
,并在程序中使用它以使其具有可扩展性。。。否则就值得花时间去了解他们。如果文件以非空格结尾(例如,“word”
),则会失败。与之相比啊,我看到了错误。谢谢@J.F.Sebastian