2

I'm learning C and I've encounter a behaviour that I have hard time to understand, this is in the context of an assignment but it is not the assignment itself, just to clarify.

I have a file that supposedly contains jpeg images. I open it and just for fun I want to print the content out. if I do:

int main(int argc, char *argv[])
{
    //check for invalid usage
    if (is_valid (argc, argv) == true)
    {
        printf("Check for valid file: OK!\n");
    }

    //load file
    FILE* fp = NULL;
    fp = fopen(argv[1], "r");

    //checkfile
    if (is_file_loaded(fp))
    {
        printf("checkfile completed\n");
    }

    //Printing every character
    char ch;
    while (( ch = fgetc(fp)) != EOF)
//      putchar(ch);
        printf("%c", ch);

    fclose(fp);
    printf("\ncompleted\n");
    return true;
}

It partially prints the first line and it stops! It doesn't even get to the newline.

the first few lines of this particular file are:

cs50.ly/surpriseJFIFC


"##!  %*5-%'2(  .?/279<<<$-BFA:F5;<9C



& &9999999999999999999999999999999999999999999999999"

It prints out:

cs50.ly/surprise

feof() of course returns false.

If I change char ch to int ch, all works fine.

I'm not sure I understand why is that happening. I would be grateful if someone could help me to understand what concept I am missing here.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Spleen
  • 21
  • 1
  • I'm trying to edit this message to add a "dear community" at the beginning but it doesn't work. sorry I did not mean to sound rude without an initial greeting. – Spleen Jun 07 '20 at 18:09
  • 1
    printing out a jpeg file like that will not work because it is a binary file that contains all kinds of ascii values including \0 and eof. try running on a text file instead alt. write out the bytes you read as decimal values. – AndersK Jun 07 '20 at 18:11
  • fgetc returns an int, it is not surprising that things work when you declare the correct return types. a char can never == EOF – pm100 Jun 07 '20 at 18:18

0 Answers0