开发者

putc giving segmentation fault?

The following code is giving segmentation fault....Why ????? event tried with fputc

I think there might be a silly error i am not able to get..but don't have enogh time.

Please help...

  开发者_开发问答 #include <stdio.h>

    int main () {

  //      system("sudo openssl enc -base64 -in file.txt -out file.txt.enc");

    FILE *fp,*fq;
    char ch;

    fp = fopen("file.txt.enc","r");
    fq = fopen("output.txt","w");

    while( (ch=fgetc(fp)) != EOF)
            putc(ch,fq);

    return 0;

    }


  1. You have to declare ch as int. Otherwise, the processing of the file will stop when the character ÿ appears. char can take only 256 different values, which is not enough for 256 different symbols + the EOF character. EOF is -1, which is equivalent to 4,294,967,295 when treated as an int, but it's equivalent to 255 when treated as a char. If your input file contains the character ÿ (essentially -1 or 255 when treated as signed), the statement ch == EOF will become true and your while loop will break. This has nothing to do with your error, but it's important nonetheless...

  2. If your program crashes, it tries to read from / write to the NULL pointer because the input file couldn't be read (doesn't exist) or the ouput file couldn't be written to (write protected).

Try:

#include <stdio.h>

int main () {

    FILE *fp,*fq;
    int ch;

    if( (fp = fopen("file.txt.enc","r")) == NULL)
        return 1;

    if( (fq = fopen("output.txt","w")) == NULL)
        return 1;

    while( (ch=fgetc(fp)) != EOF)
        putc((char) ch, fq);

    return 0;

}


Probably one of your fopen calls failed. You didn't bother to check whether or not they succeeded.

When fopen fails a null pointer is returned. If you try to use that subsequently then your program will likely bomb.

You will then have to fix the bug that Blagovest describes, and you should, of course, close your files.


fgetc returns int, not char. The purpose of that is to be able to return EOF and distinguish that from a character that's read.

Just declare ch as an int.


Check this out and read my answer http://www.cplusplus.com/reference/clibrary/cstdio/fgetc/

     Fgetc() \\ returns a signed int value

and you have declared ch as char make it as int and try it out. it will work Probably you have to check out what really the fopen is returning to you, may be its because fopen failed . its working fine on my gcc


ch must be integer. See man fgetc and man putc.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜