Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fopen c with multiple files

Tags:

c

fopen

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);
like image 308
phcaze Avatar asked May 19 '12 10:05

phcaze


People also ask

Can you fopen multiple files?

Sure. Put your fopen / fclose calls in a foreach loop against a list of files. Hardly complex.

Can you have multiple files open at once in C?

Using Multiple Files -- C++ It is possible to open more than one file at a time. Simply declare and use a separate stream variable name (fout, fin, fout2, fin2 -- file pointer) for each file.

How many files can be opened at the same time in ANSI C?

In this article The C run-time libraries have a 512 limit for the number of files that can be open at any one time. Attempting to open more than the maximum number of file descriptors or file streams causes program failure.

How is fopen () used in C?

The fopen() method in C is a library function that is used to open a file to perform various operations which include reading, writing etc. along with various modes. If the file exists then the particular file is opened else a new file is created.


1 Answers

  1. 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 ?

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

  3. 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.

like image 111
Jay D Avatar answered Oct 29 '22 15:10

Jay D