[Solved] Segmentation fault (with file on C)


What people are trying to point at in the comments is. When a system call is made, the return value should be checked, to make sure if it was executed successfully or not. In your case, the open system call can fail for a number of reasons. In that case you would have an invalid file descriptor in the variable fichier. Using which can result into a seg fault, which you are getting.

    #include <stdio.h>
    #include <string.h>

int main(int argc, const char * argv[])
{

   char example[100];
   char user[100]="user";
   char str[]="module_extension/";
   FILE* fichier=NULL;


   strcpy(example,str);
   strcat(example,user);
   strcat(example,".txt");
   fichier=fopen(example,"a+");
   if( fichier != NULL)
   {
       fprintf(fichier,"**************New Line************ \n");
       fclose(fichier);
   }
   else
       printf("File open failed");

   return 0;
}

In this way, you can make your program fail proof, even when the system call fails.

0

solved Segmentation fault (with file on C)