2014-02-17 73 views
1

已經在unix中編寫了一些代碼,它通過函數來​​計算argv [1]中的單詞數。結果將返回並顯示在stdout上。當我運行我的程序時,終端掛起

當我運行它時,這個過程只是繼續下去,直到我殺了它。沒有錯誤顯示或任何東西?有人會介意只是看看。

感謝

#include <stdio.h> 
#include <stdlib.h> 
#include <fcntl.h> 
#include <unistd.h> 

//function declaration 
int countWords(char []); 

int main(int argc, char* argv []) 
{ 
    int words; 

    //check 3 entered values 
    if (argc != 3) 
    { 
    write(2,"Please enter 2 values. Seperated by Space \n", 44); 
    exit(0); 
    } 

    words = countWords(argv[1]); 
    printf("Words are %i \n", words); 
    return 0; 
} 

//function to count words 
int countWords(char a []) 
{ 
    int counter, openStream, oTest; 
    char letter; 

    openStream = open(a,O_RDONLY); 
    if (openStream < 0) 
    { 
    write(2, "Error opening specified file. \n", 32); 
    exit(1); 
    } 

    oTest = read(openStream, &letter, 1); 
    while (oTest != 0) 
    { 
    if (oTest == -1) 
    { 
     write(2, "Error reading file \n",21); 
     exit(2); 
    } 
    if (oTest == '\n' || oTest == ' ') 
    { 
     counter++; 
    } 
    } 
    close(openStream); 
    return counter; 
} 
+3

你可能在'while(oTest!= 0)'時發生無限循環,因爲你永遠不會爲'oTest'重新分配一個值 – Jordan

+0

學習如何使用'gdb'調試器**(https: //sourceware.org/gdb/download/onlinedocs/gdb/index.html) –

回答

2

你的循環,而有剩餘的輸入流的東西,但你從來沒有真正從循環內的輸入流,這意味着你的輸入流是永永遠遠剛讀超過它的第一個字符,並且你的oTest(第一個字符)永不改變。