我創建了一個類似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終止我的程序,而無需額外的輸入。
謝謝您的全面解答。它解決了我的問題。我寫了if(feof(stdin)){break; } –