I am trying to open a file in C, but I always get that it cannot open the file. I have the the following code:
int i = 0;
char delims[] = " ";
char *result = NULL;
char * results[10];
result = strtok( cmdStr, delims );
while( result != NULL ) {
results[i] = result;
i++;
result = strtok(NULL, " ");
}
printf(results[1]); // it defo shows the name file here
FILE *fp;
char ch;
if((fp = fopen(results[1],"r")) == NULL) {
printf("Cannot open file.\n");
} else {
while((ch = fgetc( fp )) != EOF) {
printf("%c", ch);
}
}
fclose(fp);
Results[1] is the name of the file. So if I have something like “show file.txt” the results[0] will be show and results[1] the file.txt.
However it does not open it on the fopen. But if I insert in the code fopen("file.txt", "r")… it works.
My best guess is that
results[1]contains a stray newline at the end. As Daniel and Jerry suggest, a cheap fix would be to include\nin the delimiter array.Unrelated: the type of
chshould beintrather thanchar.