fopen c with multiple files

c, fopen

Solution

There is an upper limit on the number of open handles for a given process. May be you have a handle leak in your program ?

Error while creating a file typically means you don't have access permission to the parent folder .

Those error log messages belong to your program . You can enhance it further. There is an `errnum` set by the os as `fopen` is essentially a system call. You can print that error number and get more info about your issue.

Problem

In my software I have to read multiple txt databases in a serial way, so I read the first, then I do something with the info I got from that file, than I open another one to write and so on. Sometimes I got an error on an opening OR creation of a file, and then I got errors on all the following opening/creation, which uses different functions, different variables, different files. So for example I call the function below, which uses two files, and I got an error "* error while opening file -%s- ..\n", then all the other fopen() in my code goes wrong! This is an example of code for one single file: ``` FILE *filea; if((filea=fopen(databaseTmp, "rb"))==NULL) { printf("* error while opening file -%s- ..\n",databaseTmp); fclose (filea); printf("---------- createDatabaseBackup ----------\n"); return -1; } int emptyFolder=1; FILE *fileb; if((fileb=fopen(databaseBackup, "ab"))==NULL) { printf("* error while opening file -%s- ..\n",databaseBackup); fclose (fileb); printf("---------- createDatabaseBackup ----------\n"); return -1; } else { int i=0; char c[500]=""; for (i=0;fgets(c,500,filea);i++) { fprintf(fileb,"%s",c); emptyFolder=0; } } fclose(fileb); fclose(filea); ```

Original source