开发者

Whats wrong with the writing to this file handle?

开发者 https://www.devze.com 2023-01-19 13:11 出处:网络
#include<stdio.h> #include<ctype.h> int main() { FILE *fpin = fopen(\"in.txt\", \"r\"); fprintf(fpin, \"hello, world!\");
#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;
}


  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!".


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消