C fopen不创建新的文本文件,返回null,错误代码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 : %sn",cpath);        
errno = 0;
FILE * fp = fopen("data/records_file.txt","r");
printf("nfile did not existn");
if(fp == NULL){
printf("nfpen returned null, errno :%d n",errno);     
}else if(fp != NULL){ printf("nmade filen"); 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 filen");
}
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/filenname.txt"附加到它:

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

然后做:

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

但仍然得到错误代码2事实上,如果我尝试fopen(justName.txt,"r"),我仍然会返回null和错误2,所以肯定缺少一些基本的Im。可以做些什么来创建文件并让fopen工作?

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

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

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

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

您需要将"r"(表示"读取")更改为"w"(表示"写入")或"a"(表示"附加")。您可以在手册页上了解有关fopen()的更多信息。

最新更新