简体   繁体   中英

Dev-C++ Filehandling

I am using Dev-C++ IDE, and now I am trying to do the file handling.here is my code :

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;

}

this code is working in NetBeans, but in Dev-C++, I am just getting the message of "we are connected to the file", but it is not putting the value of "10" into the file. please you know the answer let me know, what should I do?

I can't see anything wrong with your code, but here are some tips

A good habit is to create functions and call these instead of having all inline eg

#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();
}

then when reading from the file I would suggest you use fgets instead as it is safer to use since fscanf has a tendency to cause memory overwrites if values are unexpected.

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

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

it works perfectly. No issue with code of IDE. please shift the code in to "My documents" in windows. Try it.... I think its permission issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM