【问题标题】:Dev-C++ FilehandlingDev-C++ 文件处理
【发布时间】:2011-05-13 01:11:52
【问题描述】:

我正在使用 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”的值放入文件中。请你知道答案告诉我,我该怎么办?

【问题讨论】:

  • @user261002;你看到任何没有内容的文件吗?还是根本没有文件?
  • 您应该做的第一件事是切换 IDE。 DevC++ 已经死了,还有更好的替代品(Visual Studio express、Code::Blocks 等)
  • 它创建了文件,但没有写入文件。

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


【解决方案1】:

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

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

#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

【讨论】:

    【解决方案2】:

    完美运行。 IDE代码没有问题。请将代码移入 Windows 中的“我的文档”。试试看....我认为它的权限问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-14
      • 2010-10-23
      • 2016-11-12
      • 2010-09-20
      相关资源
      最近更新 更多