#include<stdio.h>
#include<ctype.h>
int main() {
FILE *fpin = fopen("in.txt", "r");
fprintf(fpin, "hello, world!");
fclose (fpin);
char c;
f开发者_StackOverflow社区pin = 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.
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!");
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;
}
- Change your
char c;
toint c;
--fgetc
returns an int. - Check the return value of calls to
fopen
to see if you get a NULL return. - Change the mode of the first
fopen
to"w"
so you can write to the file. - You may want to consider adding a
\n
to the end of"hello world!"
.
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.
精彩评论