无法读取strtok函数生成的字符串

时间:2017-01-19 07:01:18

标签: c

 #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);}

这两个函数采用一个字符串(在这种情况下,字符串总是“loaddungeon dfile.txt”)这两个函数几乎完全相同,除了一个微小的区别。在第二个函数中,我将token2更改为“dfile.txt”。

第一个功能打印出“无法打开文件”

,而第二个函数成功读取文件。

但我尝试在第一个函数中打印token2,如下所示

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

打印“dfile.txt”。

怎么会发生这种情况?为什么第一个函数无法读取与“dfile.txt”完全相同的token2。谁能解释一下?提前致谢。

1 个答案:

答案 0 :(得分:1)

它可能是因为token2末尾的换行符(调试器显示了它);通过fgets读取一行时,读入的字符串通常在末尾包含一个新行字符'\n'。虽然在控制台中不明显,但这个字符可能会影响其他一些功能(例如fopen,然后可能找不到该文件)。因此,删除尾随的新行(如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);}
相关问题