0

I was trying to read a file char by char but the debugger when reaches the fscanf gives back a segmentation fault error, here's my code:

int main(){
FILE *inFile;
char *carattere = NULL;

inFile = fopen("../file.txt", "r");
if (inFile == NULL){    
    return -1;
}

while(fscanf(inFile, "%c", carattere) != EOF){  //segmentation fault
    printf("%c ", *carattere);
}
fclose(inFile);
return 0;}

(I've recentely reinstalled my IDE).

Sebastian
  • 73
  • 6

2 Answers2

2

You should provide some space for your character to be read. Where does carattere point to when you try to write into it?

Remo.D
  • 16,122
  • 6
  • 43
  • 74
1

carattere is NULL, which cannot store even a single character. So, you need to give it some memory at least 2 bytes, 1st byte for the character itself and 2nd byte for '\0'.

So, initialize carattere like this:

char carattere[2] = { 0 };
Darth-CodeX
  • 2,166
  • 1
  • 6
  • 23