编写一个打开文件并显示该文件的C语言程序:
代码如下:
//第41个程序--打开一个文件并显示该文件
#include<stdio.h>
#include<stdlib.h>
int main(void) //为了使用exit()函数
{
int ch;
FILE* fp;
char fname[50]; //存储文件名
printf("Enter the name of the file: ");
scanf_s("%s", fname);
fp = fopen_s(fname, "r"); //打开待读取文件
if (fp == NULL) //如果失败
{
printf("Failed to open file. Bye\n");
exit(1); //退出程序
}
//getc(fp)从打开的文件中获取一个字符
while ((ch = getc(fp)) != EOF)
putchar(ch);
fclose(fp); // 关闭文件return 0;
}
报错情况:(编码环境vs2022)
在visual C++6.0环境下运行正常。(注意此处的代码有所更改,需要将scanf_s改为scanf,fopen_s改回fopen,因为vs2022环境下回报错scanf和fopen会不安全)
疑惑:
头一次碰到参数太少的报错,不解,求解答,谢谢!