首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Dev-C++文件处理

Dev-C++文件处理
EN

Stack Overflow用户
提问于 2010-11-20 18:34:46
回答 2查看 12.5K关注 0票数 0

我正在使用Dev-C++集成开发环境,现在我正在尝试创建文件handling.here is my code:

代码语言:javascript
复制
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“的值放入文件中。请你知道答案,让我知道,我该怎么办?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2010-11-20 19:20:05

我看不出您的代码有任何错误,但这里有一些提示

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

代码语言:javascript
复制
#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有可能导致内存覆盖。

代码语言:javascript
复制
<- fscanf(fp," %d ", &f );

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

Stack Overflow用户

发布于 2017-12-11 18:49:35

它工作得很完美。IDE的代码没有问题。请将代码移到windows中的“我的文档”中。试试看...我认为这是一个许可问题。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4232295

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档