0
 #Function1       
    char command[256];
    char *token;
    char *token2;
        const char s[2] = " ";

    fprintf(stdout, "$ Please enter a command \n");
    fflush( stdout );
    fgets ( command, 256, stdin );
    token = strtok(command, s);
    token2 = strtok(NULL, s);

    if ((fp= fopen(token2, "r")) == NULL) {
        printf("cannot open file");
        exit(1);}

#Function 2

    char command[256];
    char *token;
    char *token2;
        const char s[2] = " ";

    fprintf(stdout, "$ Please enter a command \n");
    fflush( stdout );
    fgets ( command, 256, stdin );
    token = strtok(command, s);
    token2 = strtok(NULL, s);

    if ((fp= fopen("dfile.txt", "r")) == NULL) {
        printf("cannot open file");
        exit(1);}

These two functions take a string(in the case, the string is always "loaddungeon dfile.txt") These two functions are pretty much the same except for one tiny difference. In the second function, I changed the token2 to "dfile.txt".

The first function prints out "cannot open file"

while the second function successfully reads the file.

but I tried to print the token2 in the first function as followed

printf("%s\n", token2);

it prints "dfile.txt".

How could this happen? Why the first function cannot read the token2 which is exactly the same as "dfile.txt". Can someone explain? Thanks in advance.

zhangdi
  • 119
  • 1
  • 11

1 Answers1

1

It's propably because of the newline at the end of token2 (the debugger showed it); When reading in a line through fgets, the string read in it often contains a new line character '\n' at the end. This character may, though not obvious in the console, influence some other functions (e.g. fopen, which might not find the file then). Hence, remove the trailing new line (as described in this SO answer):

token2 = strtok(NULL, s);

char *eol;
if (token2 && (eol=strchr(token2,'\n')))
    *eol = 0x0;

if ((fp= fopen(token2, "r")) == NULL) {
    printf("cannot open file");
    exit(1);}
Community
  • 1
  • 1
Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58