c - Dev-C++ 文件处理

标签 c file file-handling dev-c++

我正在使用 Dev-C++ IDE,现在我正在尝试进行文件处理。这是我的代码:

int main(){
     FILE *fp;
     int b = 10;
     int f;
      fp = fopen("data.txt", "w");
      //checking if the file exist
      if(fp == NULL){
        printf("File does not exist,please check!\n");
      }else{
      printf("we are connected to the file!\n");
      }
      fprintf (fp, " %d ", b) ;
      fclose(fp);
      printf("Reading from the file \n");

      FILE *fr;
      fr=fopen("data.txt","r");
      fscanf (fr, " %d ", &f) ;
      fclose(fr);
      printf("the data from the file %d \n", f);
    return 0;

}

这段代码在NetBeans中工作,但在Dev-C++中,我只是收到“我们已连接到文件”的消息,但它没有将“10”的值放入文件中。请知道答案的请告诉我,我该怎么办?

最佳答案

我看不出你的代码有什么问题,但这里有一些提示

一个好习惯是创建函数并调用它们,而不是全部内联,例如

#define FILENAME "data.txt"

void writeFile()
{
     FILE *fp;
     int b = 10;
      fp = fopen(FILENAME, "w");
      //checking if the file exist
      if (fp == NULL)
      {
        perror("File could not be opened for writing\n");
      }
      else
      {
        printf("File created\n");
      }
      fprintf (fp, " %d ", b) ;
      fclose(fp);
}

void readFile()
{
     int f;
     printf("Reading from the file \n");

     FILE *fr;
     fr=fopen(FILENAME,"r");
     fscanf (fr, " %d ", &f) ;
     fclose(fr);
     printf("the data from the file %d \n", f);
}

int main()
{
  writeFile();
  readFile();
}

那么当从文件中读取时,我建议你使用 fgets 代替 因为 fscanf 有导致内存覆盖的倾向,所以使用起来更安全 如果值是意外的。

<- fscanf(fp," %d ", &f );

-> char buf[16]; // some buffer
-> fgets( fp, buf, 10 ); // read as string
-> f = atoi(buf); // convert to int

关于c - Dev-C++ 文件处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4232295/

相关文章:

c++ - -O3 打开时 SSE 中的段错误

java - 读取文件时出现 ArrayIndexOutOfBoundsException

c - 如何通过c中的文件处理访问文件夹中的特定文件

c - 名字不会显示

从 RGB 转换为灰度时 cvCvtColor 崩溃

c++ - CPP + 正则表达式来验证 URL

c# - 通过 TCP 发送/接收文件

ios - 读取存储在 Xcode 项目中的文件

c - 使用 C 代码复制 .dat 文件时出现额外字符

java - 为什么使用 file.delete() 函数无法删除文件?