views:

113

answers:

4
#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.

+10  A: 

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!"); 
Guillaume
And if that's not the segv, you're not checking the return value of the second fopen so since the first doesn't create it, the second will fail and you'll have a NULL pointer in fpin...
Paul
+4  A: 

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;
}
JaredPar
A: 

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.

Martin B
+3  A: 
  1. Change your char c; to int c; -- fgetc returns an int.
  2. Check the return value of calls to fopen to see if you get a NULL return.
  3. Change the mode of the first fopen to "w" so you can write to the file.
  4. You may want to consider adding a \n to the end of "hello world!".
bstpierre
+1: And I'd also add: 5. compile with all warnings on; 6. If you ask questions on SO give a more precise description of the error (in which line did your error occur...)
Jens Gustedt