Reputation: 11
#include<stdio.h>
#include<ctype.h>
int main() {
FILE *fpin = fopen("in.txt", "r");
fprintf(fpin, "hello, world!");
fclose (fpin);
char c;
fpin = fopen("in.txt", "r");
FILE *fpout = fopen("out.txt", "w");
while ((c = fgetc(fpin)) != EOF) {
fputc (toupper(c), fpout);
}
fclose (fpout);
fclose (fpin);
return 0;
}
I am getting a
Segmentation fault
Thank you.
Upvotes: 1
Views: 177
Reputation: 31176
char c;
to int c;
-- fgetc
returns an int.fopen
to see if you get a NULL return.fopen
to "w"
so you can write to the file.\n
to the end of "hello world!"
.Upvotes: 3
Reputation: 24130
Most likely, one of your fopen
calls is failing and returning NULL
. The most likely candidate for this is the following line:
FILE *fpin = fopen("in.txt", "r");
You probably meant to use a "w"
here, as you later try to write to the file. I'm guessing the file doesn't exist yet... and hence, when you try to open it with "r"
, the fopen
call fails.
Upvotes: 1
Reputation: 754515
They first issues that I see is that you don't check for the success of the fopen
call. It can fail and cause fpin
to be NULL which would lead to issues later on in the code.
FILE *fpin = fopen("in.txt", "r");
if (!fpin) {
printf("Error opening in.txt");
return EXIT_FAILURE;
}
Upvotes: 4
Reputation: 18865
I dont know anything about C, but is seems that you write to a file that you have opened read-only ...
FILE *fpin = fopen("in.txt", "r");
fprintf(fpin, "hello, world!");
should probably be :
FILE *fpin = fopen("in.txt", "w");
fprintf(fpin, "hello, world!");
Upvotes: 10