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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With