Segmentation error while writing file using FILE pointer

I get a “Segmentation Error” for the following C ++ code:

#include <cstdio> int main(int, char**) { FILE *fp; fp = fopen("~/work/dog.txt", "w"); fprintf(fp, "timer, timer3, timer5, timer6, timer7"); fclose(fp); } 
+4
source share
3 answers

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); } 
+9
source

A few things:

  • you need to check fp for NULL before using it, otherwise you will get segfault whenever the file is not found.

  • you need to allow the full path before passing it to fopen (fopen doesn't know what to do with "~")

Example:

 FILE *fp = NULL; char path[MAX]; char *home = getenv ("HOME"); if ( home ) { snprintf(path, sizeof(path), "%s/work/dog.txt", home); // now use path in fopen fp = fopen(path, "w"); if ( fp ) { fprintf(fp, "timer, timer3, timer5, timer6, timer7"); fclose(fp); } else { std::cout << "your dog is missing" << std::endl; } else { std::cout << "You are homeless" << std::endl; } 
+1
source

Segfault happens that the file you are trying to open does not exist. This has nothing to do with Qt.

Check the invalidity of "fp" and handle the error correctly. Sort of

 FILE *fp = fopen("/path/to/work/dog.txt", "w"); if (fp == NULL) { printf("File does not exist.\n"); // throw exception or whatever. } 
0
source

Source: https://habr.com/ru/post/1485848/


All Articles