Find the answer to your Linux question:
Results 1 to 3 of 3
Hello Everyone , I have written a simple piece of code for reading an Image file(.png) in c but this code doesn't seem to work properly.Can anyone help me solve ...
  1. #1
    Just Joined!
    Join Date
    Feb 2011
    Location
    Ranchi , India
    Posts
    2

    Problem in reading .png file in C

    Hello Everyone ,
    I have written a simple piece of code for reading an Image file(.png) in c but this code doesn't seem to work properly.Can anyone help me solve this problem of reading an image file in C.Code I have written is :-
    Code:
         FILE *file;
         char ch;
         
         file=fopen("img.png","r");     
         
         while((ch=fgetc(file))!=EOF )
                  printf("%c ",ch);
    When running this code , each time I'm getting the same output as
    ë P N G
    Even if the file size is 2022bytes .Why am I not getting 2022 bytes ? Instead I'm getting only these 4 bytes as output.Please !! help.

  2. #2
    Linux Guru Rubberman's Avatar
    Join Date
    Apr 2009
    Location
    I can be found either 40 miles west of Chicago, or in a galaxy far, far away.
    Posts
    8,974
    PNG files are binary. Most of the characters are non-printing characters, so printf won't work unless you output the hex value of the character. So try this:
    Code:
    ILE *file;
         char ch;
         
         file=fopen("img.png","r");     
         
         while((ch=fgetc(file))!=EOF )
                  printf("%.02x ", ch);
    Sometimes, real fast is almost as good as real time.
    Just remember, Semper Gumbi - always be flexible!

  3. #3
    Just Joined!
    Join Date
    May 2011
    Location
    Hyderabad, India
    Posts
    4
    Hi
    First of all if you are reading from the png file and writing it in the form of characters , then you might not see all the bytes, as the png file is a binary file and many of the bytes will not be printable character. You will get EOF if some data of the png file is -1 and it will come out of the loop. you can do it like :
    Code:
    FILE *file;
    char ch;
    long size,i;
    file=fopen("img.png","r");     
    fseek(file,0,SEEK_END);
    size=ftell(file);
    fseek(file,0,SEEK_SET);
    for(i=0;i<size;i++)
    {
    ch=fgetc(file);
    printf("%x ",ch);
    }
    Regards
    Last edited by oz; 05-07-2011 at 12:41 PM. Reason: removed spam signature

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...