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

标签 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。有人可以解释一下吗?提前致谢。

最佳答案

这可能是因为 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);}

关于无法读取 strtok 函数生成的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41735645/

相关文章:

python - 在 Python 和 C 之间共享文件流

c - 限制日志/缓冲区文件中的行数

c - 如何检测malloc失败?

c++ - LZ4:压缩图像格式的压缩

c - 除以 2 与乘以 0.5 后的结果之差

c - (c/c++) 日/月/年 hh :ii:ss to unix timestamp

c - C语言用函数取值、求最大值、求最小值并显示

c - Pop 在特定函数中仅起作用一次

c++ - _Complex 和 std::complex 之间的 C/C++ 互操作

c - urxvt 中的 ncurses 不打印重复字符