chandhooguy
chandhooguy

Reputation: 442

Segmentation fault only for one file?

So I am trying to read the input from one file(ride.in), do a calculation with it, and print the result out in another file(ride.out). When I try with the first file using fscanf, it works fine. It also works when I am just printing using printf. However, it fails to work when I try to write to the file using fprintf, resulting in Segmentation Fault: 11. How is this even possible?

Code that works:

#include <stdio.h>
#include <stdlib.h>
int main () {
FILE *fin  = fopen ("ride.in", "r");
FILE *fout = fopen ("ride.out", "w");

char UFO[6], group[6];

fscanf(fin, "%s", UFO);
int sumUFO = 0, sumGroup = 0;

for(int i = 0; i < 6; i++){
    sumUFO += (int) UFO[i];
}

fscanf(fin, "%s", group);

for(int i = 0; i < 6; i++){
    sumGroup += (int) group[i];
}

fclose(fin);

if(sumUFO == sumGroup)
    printf("GO");
else
    printf("STAY");

exit (0);
}

However, when I change the last if statement to use fprintf instead of printf, I get a Segmentation Fault: 11. This is the last if statement. Nothing else has been changed:

if(sumUFO == sumGroup)
    fprintf(fout,"GO");
else
    fprintf(fout,"STAY");

Input ride.in currently looks like:

AAAAAA
AAAAAA

Output ride.out is currently an empty text file.

Upvotes: 1

Views: 103

Answers (2)

Sudip Das
Sudip Das

Reputation: 1208

  1. after calling 1st fscanf() it is reading 6 char bt when u r calling 2nd fscanf() it is not finding the pointer from where next char have to read. for that u have to use lseek().

here is the code =>

#include <stdio.h>
#include <stdlib.h>
int main () {
FILE *fin  = fopen ("ride.in", "r");
FILE *fout = fopen ("ride.out", "w");
int i;
char UFO[6], group[6];

fscanf(fin, "%s", UFO);
int sumUFO = 0, sumGroup = 0;

for(i = 0; i < 6; i++){
 sumUFO += (int) UFO[i];
 printf("%c => %d \n",UFO[i],sumUFO );
}
fseek(fin,6,SEEK_SET);

fscanf(fin, "%s", group);
for(i = 0; i < 6; i++){
 sumGroup += (int) group[i];
 printf("%c =>> %d \n",group[i],sumGroup );

}

fclose(fin);

if(sumUFO == sumGroup)
 fprintf(fout,"GO");
else
 fprintf(fout,"STAY");

return 0;
}

in this code fprintf() is working fine ....

Upvotes: 1

keithmo
keithmo

Reputation: 4943

You're reading a 6 character string into a 6 character array. Make your arrays one larger so there's room for the terminating null. Also, "%6s" would be a much safer format specifier for fscanf (otherwise you risk a buffer overflow if the input file is malformed).

Upvotes: 3

Related Questions