Monday, 23 May 2016

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




this is the program:



#include 
#include
#include //mkdir
#include //printf
#include //error number
#include //access
#include //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();
}



Im trying to make make a program in C language that creates a text file called "records_file" in the directory "data". "data" directory is located in the working directory that contains this programs source code and exe.



the program first checks if the file and data directory exists and prints out string confirming this if so. This works fine. when I remove the text file from data directory program calls the fopen function (Ive looked around and fopen seems to be standard way of creating file - is there a different one?)



but the result returned by function is null, and checking errno I see it is 2, no such file or directory. So I wonder am I giving the correct path.
I try fopen(./data/fileName.txt,"r") , fopen(data/filename) both same result



I try to get current working directory and append "data/filename.txt" to it:




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


and then do:



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



but still get error code 2
Actually if I try to do fopen(justName.txt,"r") I still get null returned and error 2, so there must be something basic Im missing. What can be done to create the file and get fopen to work?


Answer



If you want to write a file, as you are trying to do at:



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


and




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


and



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


You need to change the "r" (for "read") to a "w" (for "write") or "a" (for "append"). You can learn more about fopen() at the man page.



No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...