2015-04-05 79 views
0

我有下面的代碼(不是我的)試圖讓它工作出好奇。 從這裏C low-level standard-in to accept filename then printing file contents to stdout無法獲取文件使用讀取/ fgets /寫入標準輸出在C

int checkfile(void) 
{ 
    char buffer[4096]; 
    char userInput[100]; 
    int input_file1; 
    int n; 

    /* Check file existence. */ 

    printf("Enter the filename: \n"); 
    fflush(NULL); 

    if (!fgets(userInput,sizeof(userInput),stdin)) 
    { 
     perror("fgets"); 
     exit(EXIT_FAILURE); }; 

    if((input_file1 = open(userInput, O_RDONLY)) < 0) 
    { 
     perror(userInput); 
     exit(1); 
    } 

    while((n = read(input_file1, buffer, sizeof(buffer))) > 0) 
    { 
     if((write(STDOUT_FILENO, buffer, n)) < 0) 
     { 
     perror("failed to display file to output"); 
     close(input_file1); 
     exit(1); 
     } 
    } 
} 

每當我運行的代碼,並嘗試打開一個名爲「success.txt」我得到一個分段錯誤

"RUN FINISHED; Segmentation fault; core dumped; real time: 3s; user: 0ms; system: 0ms" 

我也從我的主要代碼調用此as

checkfile(); 

如果這有什麼區別。

有人能指出我失蹤的原因,因爲此刻我看不到它。我有一種感覺,我的一些變量設置不正確......但不確定謝謝。

回答

3
if (!fgets(userInput,sizeof(userInput),stdin)) 

在幾個帳戶上是錯誤的。

  1. userInput不指向任何有效的內存。
  2. sizeof(userInput)sizeof(char*)相同,這不是你想要的。

變化

char *userInput; 

喜歡的東西:

char userInput[100]; 

下一個問題是

if((input_file1 = open(userInput, O_RDONLY)) < 0) 

這是不對的。 open的返回值是intinput_file1的類型是FILE*。我很驚訝你沒有收到編譯器錯誤/警告。

變化

FILE *input_file1; 

int input_file1; 

而接下來的問題

它可能造成fgets()包括userInput換行符。添加代碼以修剪換行符。

int len = strlen(userInput); 
if (userInput[len-1] == '\n') 
{ 
    userInput[len-1] = '\0'; 
} 
+0

好的真棒,那解決了我的seg故障。現在它已經成功完成,但仍然不顯示我的文件的內容,只是進入我的主要功能中的下一代代碼?似乎它不寫入標準輸出 – LewisFletch 2015-04-05 06:19:47

+0

是的,沒有得到編譯器錯誤。所以更新後的那一段代碼我現在得到「沒有這樣的文件或目錄」,即使該文件位於編譯文件夾的根目錄..?任何想法,爲什麼這可能是?對不起仍然包裹我的頭文件處理...謝謝@ R Sahu – LewisFletch 2015-04-05 06:30:33

+0

@LewisFletch,看到第二次更新。 – 2015-04-05 06:33:36