为什么我不能用C语言的fgets读取字符串?

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;
 }

我在文件中打印了 "This is an example.","Example.dat" 我想通过上面的代码从文件中再次读取它,但是输出中没有字符串。为什么?请帮助我。

您正在以只写模式打开文件 ("w")。使用 "w+" 进行读写。

FILE *File_fp = fopen("Example.dat", "w+");

要读取文件,您必须使用模式"r"。例子: FILE *File_fp = fopen("Example.dat", "r");

你在这段代码中犯了一个错误。如果创建文件失败,fopen() 函数将 return NULL。那么文件指针的值将是NULL。 因此,在您的代码中,if section 将在成功创建文件时执行。因此,像这样更改您的代码:

if(File_fp)
 {
  printf("An error occurred while creating the file.\n");
  exit(1);
 }

只需删除 (!) 逻辑非 符号。