"Segmentation fault" error while running C program on linux shell

Asked

Viewed 116 times

-1

I have the following program in C language:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main (int argc, char *argv[]){
    FILE *p;
    char str[30], frase[]="Nome do arquivo :", resposta [80];
    int i;
    printf("Informe o nome do arquivo :\n");
    fgets(str ,20,p);
    for(i=0; str[i];i++)
    if(str[i]== ’\n’)
    str[i]=0;
    if (!(p=fopen(str ,"w"))){
      printf("Erro! Não é possível abrir o arquivo. \n");
      exit (1);
    }
    fputs(frase ,p);
    fputs(str ,p);
    fclose(p);
    p = fopen(str ,"r");
    fgets(resposta,atoi (argv[1]) ,p);
    printf("%s \n", resposta );
    fclose(p);
    return (0);
}

I am compiling through gcc of linux. I already made several changes, I increased the size of char lists and even then the error "segmentation fault" persists right at the start of the execution.

Could someone help me?

1 answer

0


There’s no point in you passing the variable p that comes from FILE *p to the fgets() if the intention is to get the input "typed by the user", the error occurs precisely because the variable p is not "manipulating" anything yet, so fgets() don’t understand what "you want to do".

If the intention is to get the "input" the right would be to read the stdin, something like:

printf("Informe o nome do arquivo :\n");
fgets(str ,20, stdin);

But I don’t think this is his only problem for(i=0; str[i];i++) is without the keys {...}, I believe he even runs the third line of:

for(i=0; str[i];i++)
if(str[i]== ’\n’)
str[i]=0;

But any mistake or change your code will break and something else, which may be from your text editor, the apostrophes seem to be wrong, if they are really wrong you will probably get:

error: non-ASCII characters are not allowed outside of literals and identifiers
if (str[i] == ’\n’)
              ^
  • Thank you so much! I knew that the problem would be in this line pq when I used only gets() worked, but using fgets is much better.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.