![](/img/trans.png)
[英]Why I cannot use "fgets" to read a string to an element of my Struct?
[英]Why cannot I read string by fgets in C programming language?
我有这个代码工作:
#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”中,我想通过上面的代码从文件中再次读取它,但 output 中没有字符串。 为什么? 请帮我。
您正在以只写模式(“w”)打开文件。 使用“w+”进行阅读和写作。
FILE *File_fp = fopen("Example.dat", "w+");
要读取文件,您必须使用模式“r”。 示例: FILE *File_fp = fopen("Example.dat", "r");
你在这段代码中犯了一个错误。 如果创建文件失败, fopen() function 将返回NULL 。 那么文件指针的值就是NULL 。 因此,在您的代码中if 部分将在文件成功创建时执行。 因此,像这样更改您的代码:
if(File_fp)
{
printf("An error occurred while creating the file.\n");
exit(1);
}
只需删除(!) 逻辑非符号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.