2013-11-26 41 views
-1

我想用C,在C.計劃在C

模擬wc命令寫一個程序這是我所模擬WC的命令,但它返回總是0

有人可以幫助我直了這一點,因爲我不是很熟悉C.

#include <stdio.h> 
#include <string.h> 
#include <unistd.h> 


int main(int argc, char** argv) 
{ 
int bytes = 0; 
int words = 0; 
int newLine = 0; 
char buffer[1]; 
enum states { WHITESPACE, WORD }; 
int state = WHITESPACE; 
if (argc !=2) 
{ 
    printf("Help: %s filename", argv[0]); 
} 
else{ 
    FILE *file = fopen(argv[1], "r"); 

    if(file == 0){ 
     printf("can not find :%s\n",argv[1]); 
    } 
    else{ 
      char *thefile = argv[1]; 
     char last = ' '; 
     while (read(thefile,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,thefile);   
    } 
} 

} 
+0

也許你需要兩個變量:'枚舉指出currentState,previousState;''如果((currentState == WORD)&&(previousState == WHITESPACE))字樣++;' –

回答

2

read(2)接受文件描述符作爲第一個參數,而不是文件名

while (read(thefile,buffer,1) ==1) 

應該

while (read(fileno(file),buffer,1) ==1) 

BTW:啓用和閱讀編譯器警告將指向你這種錯誤

編輯:

混合系統調用(read(2))和高層次的功能(fopen(3))通常不是一個好主意;請使用fread(buffer, 1, 1, file)或打開文件與open(2)

+1

或.. 。只需使用['fgetc'](http://en.cppreference.com/w/c/io/fgetc) – paddy

+0

謝謝ensc,這就是訣竅。 – Leon