gpt4 book ai didi

c - 文件中的单词计数,如 C 中的 linux wc 命令

转载 作者:太空宇宙 更新时间:2023-11-04 02:11:51 24 4
gpt4 key购买 nike

我正在尝试编写一些类似于 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);
}
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;
}
}

关于c - 文件中的单词计数,如 C 中的 linux wc 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13039023/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com