Results 1 to 4 of 4

Thread: Opening and reading binary files in C?

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    Sep 2001
    Posts
    396

    Question Opening and reading binary files in C?

    Last year, I have written an unsuccessful program. Well since I am here now, might as well pop the question here.

    This program is supposed to open a file(size unknown at compile time) in binary.

    I had to open the file in binary bcos I opened in text mode, the \n and \r characters are taken away. It is an binary file.

    The program is supposed to read the bytes and convert each byte into 2 hex character(ie 2 hex byte (0-f) to represent the byte) and save it in a 2nd file.

    But the program do not recongnise EOF and was non-stop, and I got to ctrl break and if I do not do so. The 2nd file will occupy my whole harddisk.

    If I open the source file in text mode, no such problem.

    Is it bcos it have mistaken EOF as one of the normal bytes in the source file in binary mode.

    Well the compiler in question is TC 3.0.

    Sorry, I do not have the source code with me already.(wiped off from the surface of my harddisk long ago)
    I'm a VB6 beginner.

  2. #2
    Monday Morning Lunatic parksie's Avatar
    Join Date
    Mar 2000
    Location
    Mashin' on the motorway
    Posts
    8,169
    Well, use fopen(filename, "rb") to open for reading, and just keep reading from the file until fread(...) returns a value less than 1 (0 means nothing read, -1 I think is an error code).
    I refuse to tie my hands behind my back and hear somebody say "Bend Over, Boy, Because You Have It Coming To You".
    -- Linus Torvalds

  3. #3
    jim mcnamara
    Guest
    Expanding on Parksie's note -

    Code:
    #include <stdio.h>
    
    void main(void){
            unsigned char ch;
            int linecounter=0;
            FILE *in;
            in = fopen("myfile.dat","rb");
            if(ferror(in) ){
                  perror("Error opening input file:");
                  exit(1);
            }
            while (!feof(in) ){
                   if(  fread(&ch,sizeof(ch),1,in) ==1){
                        /* do stuff with the character you just read */
                        printf("%X ",ch);
                        linecounter++;
                        if ( !(linecounter%30) ) 
                                printf("\n");
                    }
            }
            fclose(in);
    }

  4. #4

    Thread Starter
    Hyperactive Member
    Join Date
    Sep 2001
    Posts
    396
    Thanks parksie & jim for taking time to read my post and answer them.
    I'm a VB6 beginner.

Posting Permissions

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



Click Here to Expand Forum to Full Width