C fopen不会创建新的文本文件,返回null,错误代码2

时间:2017-01-08 20:33:36

标签: c file io fopen

这是该计划:

#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语言创建一个程序来创建一个名为&#34; records_file&#34;的文本文件。在目录&#34;数据&#34;。 &#34;数据&#34; directory位于包含此程序源代码和exe。

的工作目录中

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

但是函数返回的结果是null,并且检查errno我看到它是2,没有这样的文件或目录。所以我想我是否给出了正确的道路。 我尝试fopen(./ data / fileName.txt,&#34; r&#34;),fopen(data / filename)两个结果相同

我尝试获取当前工作目录并附加&#34; data / filename.txt&#34;它:

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,&#34; r&#34;)我仍然得到null返回错误2,所以必须有一些基本的我遗漏。如何创建文件并让fopen工作?

1 个答案:

答案 0 :(得分:1)

如果你想写一个文件,正如你想要的那样:

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

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

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

您需要将"r"(用于“阅读”)更改为"w"(用于“写入”)或"a"(用于“追加”)。您可以在man page了解fopen()的更多信息。