Your path is invalid and will never work, so fopen sets fp to NULL and you get segfault. Hint: the ~ character ~ expanded by the shell, you cannot use it in the fopen argument.
The correct, safe implementation of what you are trying to do might look like this. This is verified. This is also the reason why sane people don’t write in C unless they have another way to do it :)
// main.cpp #include <cstdio> #include <cstdlib> #include <cstring> #include <unistd.h> int main(int, char**) { const char * home = getenv("HOME"); if (home == NULL || strlen(home) == 0 || access(home, F_OK) == -1) abort(); const char * subPath = "/work/dog.txt"; char * path = (char*)malloc(strlen(home) + strlen(subPath) + 1); if (path == NULL) abort(); strcpy(path, home); strcat(path, subPath); FILE *fp = fopen(path, "w"); if (fp != NULL) { fprintf(fp, "timer, timer3, timer5, timer6, timer7"); fclose(fp); } free(path); }
source share