在unix中执行wc命令的程序。字数错误

时间:2015-05-05 17:15:51

标签: c unix

我的字数输出有问题。有时候它会把空间算作一个单词。

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]);   

 }

谢谢

1 个答案:

答案 0 :(得分: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.