Strings in C are not like other strings in other high-level languages; that is, You have to allocate all the space for them yourself. When using c-string functions, you need to ensure that you have enough memory allocated for the resultant strings, by either reserving enough space on the stack (i.e. char filename[HOPEFULLY_ENOUGH]) or via the heap (malloc() and friends). You cannot count on getenv
to return a string with enough space for you to concatenate to;
Here's a complete program from start to finish that does what you want to do (minus some pedantic error checking):
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
char *filename = "/dataNumbers.txt";
char *writeString = "TEST";
char *home_dir = getenv("HOME");
char *filepath = malloc(strlen(home_dir) + strlen(filename) + 1);
strncpy(filepath, home_dir, strlen(home_dir) + 1);
strncat(filepath, filename, strlen(filename) + 1);
printf("%s\n", filepath);
FILE *myFile = fopen(filepath, "w");
fwrite(writeString, 1, strlen(writeString), myFile);
fclose(myFile);
free(filepath);
return 0;
}
strncpy will copy the string plus the null terminator (that's the reason for the +1
). strncat will begin concatenation at the null terminator and the resultant concatenated string itself must be null-terminated (hence the +1
in the third argument to strncat).
I use malloc and free because it's hard to know exactly the length of the full path to your file. You could go with something enormous (like char[4096]) but that seems wasteful, doesn't it? malloc() allows you to reserve exactly the amount of memory you need. No more, and no less.
You can also do the string concatenation using the snprintf function. I include this only for your personal enrichment, and sometimes it's nice to have multiple ways to do the same thing, even though strcpy and strcat will make your intentions much more clear to readers of your code:
char *filename = "/dataNumbers.txt";
char *writeString = "TEST";
char *home_dir = getenv("HOME");
size_t size = strlen(home_dir) + strlen(filename) + 1;
char *filepath = malloc(size);
snprintf(filepath, size, "%s%s", home_dir, filename);
Hope this helps!