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

时间:2018-11-04 16:16:05

标签: c recursion fopen descriptor fputs

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

我没有正确的答案,如果我想在打开文件后执行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语言的初学者,我已经读过很多关于指针的YouTube,但我没有弄错。

提前谢谢

1 个答案:

答案 0 :(得分:3)

您使用privkey.pem打开了文件,但仍在尝试写入。您需要使用"r"