Bad file descriptor after recursive function to open file in C

1.1k views Asked by At

I want to do a error check in a openFile Function in C and on errno:2 I want to recursivly call again the same function.

I don't get the right answer, if I want to do fputs() after opened the file I get a Error (Bad file descriptor)

Here is my code:

void openFile(FILE **fstream, char* path, char* mode) {
    *fstream = fopen(path, mode);
    if(*fstream == NULL) {
        printf("\nError number %2d : ",errno);
        perror("Error opening file: ");
        switch (errno) {
            case 2:
                printf("Creating file %s now...\n", path);
                *fstream = fopen(path, "a+");     //Creating file in append-mode
                if (fstream == NULL) {
                    perror("Couldn't open the file!\nError");
                    exit(EXIT_FAILURE);
                }
                fclose(*fstream);                 //Closing filestream
                openFile(fstream, path, mode);    //Recursive call of openFile() to re-open in read-mode
                /* freopen(path,mode,fstream) */  //Doesn't work either
                break;
            default:
                exit(EXIT_FAILURE);
                break;
        }
    } else if (*fstream != NULL) {
        printf("Successfully opened %s\n", path);
    }
}

The call:

   openFile(&fp, path,"r");
   if (fputs("blabla\nblabla\n",fp) == EOF) {
     perror("Unable to write file with fputs()"); 
   }

What I'm doing wrong? I think it's at the point of the recursive call of the function, but what I have to do here? I don't get it..

Output is:

> .\a
Content of path: test.txt
Error number  2 : Error opening file: : No such file or directory
Creating file test.txt now...
Successfully opened test.txt
Unable to write file with fputs(): Bad file descriptor

PS: I am a beginner with C, I've read and youtubed a lot about pointer, but I don't get the mistake.

Thank you in advance

1

There are 1 answers

2
Cyber On BEST ANSWER

You opened the file with "r" yet you're attempting to write. You need "w" instead.