我有这个代码工作:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
FILE *File_fp = fopen("Example.dat", "w");
char Temporary[50];
if(!File_fp)
{
printf("An error occurred while creating the file.\n");
exit(1);
}
fprintf(File_fp, "This is an example.\n");
fgets(Temporary, 49, File_fp);
printf("It was \"%s\"\n", Temporary);
return EXIT_SUCCESS;
}
我打印了“这是一个例子”。在文件“ Example.dat”中,我想通过上面的代码从文件中再次读取它,但是输出中没有字符串。为什么?请帮我。
要读取文件,必须使用模式“ r”。例:FILE *File_fp = fopen("Example.dat", "r");
您在此代码中犯了一个错误。如果创建文件失败,则fopen()函数将返回NULL。那么文件指针的值将为NULL。因此,成功创建文件后,将在代码中执行if部分。因此,像这样更改代码:
if(File_fp)
{
printf("An error occurred while creating the file.\n");
exit(1);
}
只需删除(!)逻辑非符号。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句