#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/