Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a file to users HOME directory in C

I am trying to write a .txt file to the user's HOME directory.

I have tried:

char str[] = "TEST";
char* file = strcat(getenv("HOME"), "/dataNumbers.txt"); //I am concatenating the user's home directory and the filename to be created.
myFile = fopen(file,"w");
fwrite(str , 1 , sizeof(str) , myFile );

However, this does not create the file.

like image 331
Hani Al-shafei Avatar asked Oct 28 '25 01:10

Hani Al-shafei


2 Answers

You are using strcat incorrectly.

 char *file;
 char *fileName = "/dataNumbers.txt";

 file = malloc(strlen(getenv("HOME") + strlen(fileName) + 1); // to account for NULL terminator
 strcpy(file, getenv("HOME"));
 strcat(file, fileName);

file will now contain the concatenated path and filename.

Obviously, this could be written much more cleanly. I'm just trying to be very straightforward.

like image 174
David Hoelzer Avatar answered Oct 30 '25 14:10

David Hoelzer


You can't strcat() to an environment variable. You need another buffer:

char file[256]; // or whatever, I think there is a #define for this, something like PATH_MAX
strcat(strcpy(file, getenv("HOME")), "/dataNumbers.txt");
myFile = fopen(file,"w");

EDIT To address one of the comments below, you should first ensure that the data to be concatenated doesn't overflow the file buffer, or allocate it dynamically - not forgetting to free it afterwards.

like image 31
user207421 Avatar answered Oct 30 '25 14:10

user207421