我有一个应模仿某些shell命令的程序。我应该创建的这些命令之一是cat,但是我遇到了问题。当我在一个存在的文件上运行它时,它可以工作,但是当我尝试在一个不存在的文件上运行它时,出现了分段错误。即使我以为我被告知fopen()可用于检查文件的存在而不会引起分段错误。下面是代码的cat部分的代码(有些变量早先已经声明过,例如token,但是我已经包含了一些注释来解释它们的含义,但是我可以肯定的是,这个问题与这些变量。)
if(strncmp(token, "cat", 3) == 0){
FILE* in;
char tLine[500];
char f;
//Copy the entire line of user input from earlier into a temporary char array
strcpy(tLine, inputLine);
/*Advance the char array that contains the original line of input
split by spaces to the first argument*/
token = strtok(NULL, " ");
//For storing the number of arguments
int count = 0;
//Determine number of arguments
while(token != NULL){
count++;
token = strtok(NULL, " ");
}
strcpy(tLine, inputLine);
token = strtok(tLine, " ");
token = strtok(NULL, " ");
if(count < 1){
printf("%s", "Please enter at least one argument");
}
else if (count > 1){
printf("%s", "Please only enter one argument");
}
//If there is only one argument, attempt to open the file and read its contents.
else{
in = fopen(token, "r");
if(in){
f = fgetc(in);
while(f != EOF){
printf("%c", f);
f = fgetc(in);
}
}
else{
printf("%s", "Could not open file.");
}
fclose(in);
}
}