Closed. This question is off-topic。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗? Update the question,因此它是on-topic,用于堆栈溢出。
                        
                        4年前关闭。
                                                                                            
                
        
我的字数输出出现问题。有时,它会将一个空格视为一个单词。

n = read(inFile,buffer,512);
    int i;
    for(i = 0 ; i < n; i++){
     if(buffer[i] == '\n') {
       l++;
       if(buffer[i-1] != '\n' || buffer[i-1] == EOF ){
         if(buffer[i-1] != ' '){
            w++;
        }
       }//end if
     }//end if
     if(buffer[i] == ' ' || buffer[i] == '\t'){
       w++;//get the word
     }//end if

    b++;//get the byte
  }//end for

 printf(" %d %d %d %s \n" ,l,w,b,argv[1]);

 }


谢谢

最佳答案

您对使用read返回的缓冲区检测EOF的理解是错误的。缓冲区中没有EOF字符。必须通过查看读取的返回值来检测EOF。

来自man 2 read


  返回值

 If successful, the number of bytes actually read is returned.  Upon
 reading end-of-file, zero is returned.  Otherwise, a -1 is returned and
 the global variable errno is set to indicate the error.

关于c - 在UNIX中执行wc命令的程序。错误的字数统计,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30059291/

10-11 19:33
查看更多