递归函数后在 C 中打开文件的错误文件描述符

Bad file descriptor after recursive function to open file in C

我想在 C 中的 openFile 函数中进行错误检查,在 errno:2 我想再次递归调用相同的函数。

我没有得到正确的答案,如果我想在打开文件后执行 fputs(),我会得到一个错误(错误的文件描述符)

这是我的代码:

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

来电:

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

我做错了什么?我认为这是在函数的递归调用点,但我必须在这里做什么?没看懂..

输出为:

> .\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: 我是 C 的初学者,我已经阅读并在 youtub 上看了很多关于指针的内容,但我没有弄错。

提前致谢

您使用 "r" 打开了文件,但您正在尝试写入。您需要 "w"