Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

"segmemtaion fault" in C

0 votes
asked Nov 1, 2018 by okire (250 points)
I'am beginner in C-programming and when trying to run this code - the result is "segmentation fault",  I suspect that GDB online compiler can not use "files" in C -  is that correct?

****************************************************************

#include <stdio.h>

int main () {
   FILE *fp;
   char str[80];
   
  //Open file
    if((fp = fopen("myfile.txt", "w")==NULL)){
        printf("Cannot open file\n");
        exit(1);
    }

  //writing to file
   fprintf("This is a system programming language.", fp);
   

   if((fp = fopen("myfile.txt", "r")==NULL)){
       printf("Cannot open file\n");
       exit(1);
   }

   fgets(str, 80, fp);
   printf("%s\n", str);

   fclose(fp);
   return(0);
}

*******************************************************************************

2 Answers

0 votes
answered Nov 2, 2018 by okire (250 points)
ok, got it, now it's right and its works!

****************************************

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

int main () {
   FILE *fp;
   char str[80];
   
  //Open file
   fp = fopen("myfile.txt", "w");

  //writing to file
    fprintf(fp, "This is a system programming language.");
   

    fp = freopen("myfile.txt", "r", fp);

   fgets(str, 80, fp);
   
   printf("%s\n", str);

   fclose(fp);
   
   return(0);
}

*************************************************
0 votes
answered Nov 3, 2018 by anonymous
bye bro take care
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...