2016-04-15 125 views
1

我創建了一個類似unix-shell的程序。也就是說,如果輸入類似「./helloWorld」的東西,它會執行程序,然後等待額外的輸入。如果輸入是EOF(Ctrl + D),則程序必須終止。如何比較字符串與EOF?

我在努力嘗試比較輸入而不使用getchar()或任何需要額外輸入的方法。

這裏是我的代碼:

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include<unistd.h> /* for fork() */ 
#include<sys/types.h> /* for pid_t */ 
#include<sys/wait.h> /* fpr wait() */ 

int main(int argc, char* argv[]) 
{ 
    pid_t pid,waitPid; 
    int status; 
    char fileName[256]; 
    while(!feof(stdin)) 
    { 
    printf(" %s > ", argv[0]); 
    if (fgets(fileName, sizeof(fileName), stdin) != 0) 
    { 
     fileName[strcspn(fileName, "\n")] = '\0'; //strcspn = calculates the length of the initial fileName segment, which consists of chars not in str2("\n") 

    char *args[129]; 
    char **argv = args; 
    char *cmd = fileName; 
    const char *whisp = " \t\f\r\b\n"; 
    char *token; 
    while ((token = strtok(cmd,whisp)) != 0) // strtok = breaks string into a series of tokens using the delimeter delim(whisp) 
    { 
     *argv++ = token; 
     cmd = 0; 
    }// /while 

    if (getchar() == EOF) 
    { 
    break; 
    } 

    *argv = 0; 

    pid = fork(); 
    if (pid == 0){ 
    execv(args[0], args); 
    fprintf(stderr, "Oops! \n"); 
    } // /if 
    waitPid = wait(&status); 



}// /if(fgets..) 
} // /while 
return 1; 

}

我想用一個直接比較,以取代

if (getchar() == EOF) 
     { 
     break; 
     } 

。像這樣:if(fileName == EOF){break; }

這甚至可能嗎?我已經嘗試過投射和其他方法,但迄今沒有任何工作。有沒有想過的另一種方法? 爲了更清楚一點,我想知道我的想法是否可行,以及它是如何實現的。如果不是,我怎樣才能用CTRL + D終止我的程序,而無需額外的輸入。

回答

4

沒有辦法比較字符串與EOF;它不是char的值,而是流中的條件(這裏是stdin)。然而,getchar()並都將返回char作爲unsigned char強制轉換爲intEOF文件結束,如果達到,或發生錯誤。


的手冊頁fgets說:

fgets(s, size, stream)回報s上的成功,NULL的錯誤或時,而沒有字符已經讀發生文件結束。

當您從fgets得到NULL可以使用feof(stdin)來測試你是否已經到了結束的文件;或者如果是因爲錯誤;同樣,您應該能夠在用fgets閱讀每行後檢查返回值feof(stdin)。如果feof(stdin)返回0,則文件結束還未到達;如果返回值不爲零,則表示已達到EOF。

+0

謝謝您的全面解答。它解決了我的問題。我寫了if(feof(stdin)){break; } –