C fopen 没有新建文本文件,returns null,错误代码2

C fopen does not create a new text file, returns null, error code 2

这是程序:

#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h> //mkdir
#include <stdio.h> //printf
#include <errno.h> //error number
#include <unistd.h> //access
#include <string.h> //strcat

    int makeFile(){
        printf("\n- starting makeFile function -\n");

    DIR* dirstream = opendir("data");
    if(dirstream){

        if(access("data/records_file",F_OK) != -1){
            printf("\nfile exists!\n");
        }else {  
            //char cpath[1024];
            //getcwd(cpath, sizeof(cpath));
            //strcat(cpath,"/data/records_file.txt");
            //printf("\nfull path is : %s\n",cpath);        

            errno = 0;
            FILE * fp = fopen("data/records_file.txt","r");
            printf("\nfile did not exist\n");

            if(fp == NULL){
                printf("\nfpen returned null, errno :%d \n",errno);     
            }else if(fp != NULL){ printf("\nmade file\n"); fclose(fp); }
        }

        closedir(dirstream);

    }else if(ENOENT == errno){ 
        mkdir("./data",S_IRUSR|S_IWUSR);
        FILE * fp = fopen("./data/records_file.txt","r");
        if (fp != NULL){ fclose(fp); }
        printf("\ndirectory did not exist. make dir and file\n");
    }

    printf("\n- leaving makeFile function -\n");
}


int main(){
    makeFile();
}

我正在尝试用 C 语言制作一个程序,在目录 "data" 中创建一个名为 "records_file" 的文本文件。 "data" 目录位于包含此程序源代码和 exe 的工作目录中。

程序首先检查文件和数据目录是否存在,如果存在则打印出确认字符串。这很好用。当我从数据目录中删除文本文件时程序调用 fopen 函数(我环顾四周发现 fopen 似乎是创建文件的标准方式 - 有不同的方式吗?)

但是函数返回的结果是null,查看errno是2,没有那个文件或目录。所以我想知道我是否给出了正确的路径。 我尝试 fopen(./data/fileName.txt,"r") , fopen(data/filename) 结果相同

我尝试获取当前工作目录并将 "data/filename.txt" 附加到它:

char cpath[1024];
getcwd(cpath, sizeof(cpath));
strcat(cpath,"/data/records_file.txt");
printf("\nfull path is : %s\n",cpath);  

然后做:

FILE * fp = fopen(cpath,"r");

但仍然得到错误代码 2 实际上,如果我尝试执行 fopen(justName.txt,"r") 我仍然会返回 null 和错误 2,因此我一定缺少一些基本的东西。如何创建文件并让 fopen 工作?

如果你想写一个文件,就像你想做的那样:

FILE * fp = fopen("data/records_file.txt","r");

FILE * fp = fopen("./data/records_file.txt","r");

FILE * fp = fopen(cpath,"r");

您需要将 "r"(对于 "read")更改为 "w"(对于 "write")或 "a"(对于 "append").您可以在 man page.

了解更多关于 fopen() 的信息