Ashish
Ashish

Reputation: 29

C programming - 1's complement of End of File

To start off, I am a novice in C.

I stumbled across an example, which asked the user to decrypt a c-file (which contains 1's complement of another c-file).

Normally, you would copy the characters using the following statement

    while ((ch = fgetc(fs)) != EOF)

but I am having trouble, while decrypting the file. I tried the following -

    while (~(ch = fgetc(fs)) != EOF)

the result is - the program is going into indefinite loop. I tried using the ASCII value of EOF (which is 26), but even that didn't work in my favor.

Any help would be appreciated. Thanks in advance.


/* program to decrypt the file */

Here is the full code -

    #include<stdio.h>
    #include<stdlib.h>

    void main()
    {
        FILE *fs, *ft;
        char ch;

        fs = fopen("xyz.c", "r");
        ft = fopen("xyz1.c", "w");

        if((fs == NULL) || (ft == NULL))
        {
            printf("Cannot open the file.\n");
            exit(1);
        }

        while (~(ch = fgetc(fs)) != EOF)
            fputc(~ch, ft);

        fclose(fs);
        fclose(ft);
    }

Upvotes: 0

Views: 104

Answers (2)

edmz
edmz

Reputation: 8494

EOF is a marker that signals that the end of file (or stream) has been reached. Now, such marker is not handled by you - you cannot modify it (or encrypt it, in this case), since it's internally managed by the underlying file system.

Therefore, checking for ~EOF is logically wrong and will only catch that specific value (EOF is -1 on most implementations, so ~-1 is 0).

Simply:

int ch;
while ( (ch = fgetc(fs)) != EOF )
    int decoded = ~ch;

Upvotes: 2

Keith Thompson
Keith Thompson

Reputation: 263177

You need to compare the value returned to fgetc(fs) to EOF. Only apply the ~ operator to it after you've done that comparison.

And applying ~ to the result of fgetc() is going to cause problems. For example, if you read the letter 'a', the value of ch (which needs to be an int, not char) is going to be 97 (assuming an ASCII-based system). ~97 is going to be a very large negative number, probably somewhere around -2 billion. You'll need to grab just the low-order bits of the result.

Upvotes: 0

Related Questions