0

我想openFile在 C 中的函数和 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 的初学者,我已经阅读并在 youtube 上阅读了很多关于指针的内容,但我没有弄错。

先感谢您

4

1 回答 1

3

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

于 2018-11-04T16:21:08.513 回答