#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
,然后可能找不到文件)。因此,删除尾随的新行(如本SO答案所述):
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);}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句