#include<stdio.h>
int main()
{
FILE*fp;
char ch, filename[19];//这里的19假如大于本人输入的文件名就会报错,必须刚好
errno_t err;
printf(“Please input file”s name:\n”);
fgets(filename, sizeof(filename), stdin);
err = fopen_s(&fp, filename, “r”);
if (err != 0)
{
printf(“The file %s was not opened\n”, filename);
}
while ((ch = getc(fp)) != EOF)
putchar(ch);
fclose(fp);
return 0;
}
为什么会出现这种情况,求指点啊!
int main()
{
FILE*fp;
char ch, filename[19];//这里的19假如大于本人输入的文件名就会报错,必须刚好
errno_t err;
printf(“Please input file”s name:\n”);
fgets(filename, sizeof(filename), stdin);
err = fopen_s(&fp, filename, “r”);
if (err != 0)
{
printf(“The file %s was not opened\n”, filename);
}
while ((ch = getc(fp)) != EOF)
putchar(ch);
fclose(fp);
return 0;
}
为什么会出现这种情况,求指点啊!
解决方案
40
fgets会把回车符也读进来的,所以只有当刚好等于19你才不会出错,改成scanf_s好了
#include<stdio.h> int main() { FILE*fp; char ch, filename[19];//这里的19假如大于本人输入的文件名就会报错,必须刚好 errno_t err; printf("Please input file"s name:\n"); scanf_s("%s", filename, 19); err = fopen_s(&fp, filename, "r"); if (err != 0) { printf("The file %s was not opened\n", filename); } while ((ch = getc(fp)) != EOF) putchar(ch); fclose(fp); return 0; }
40
输入没问题,只是会多接收到\n,导致打开文件失败
换用scanf函数,或将\n 去除:
#include<stdio.h> int main() { FILE*fp; char ch, filename[19];//这里的19假如大于本人输入的文件名就会报错,必须刚好 errno_t err; printf("Please input file"s name:\n"); fgets(filename, sizeof(filename), stdin); filename[strlen(filename)-1] = "\0"; err = fopen_s(&fp, filename, "r"); if (err != 0) { printf("The file %s was not opened\n", filename); } while ((ch = getc(fp)) != EOF) putchar(ch); fclose(fp); return 0; }