Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C / C++ / MFC
  4. C fread to read 512k binary file

C fread to read 512k binary file

Scheduled Pinned Locked Moved C / C++ / MFC
helpquestion
10 Posts 5 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • F Offline
    F Offline
    Fossi Bluman
    wrote on last edited by
    #1

    I use the bellow code to read binary file but it throws an exceptions at run time and sometimes gives a wrong results , please tell me what's the wrong ?

    #include
    #include

    unsigned long size,n;
    int main()
    {
    unsigned char *buf;
    FILE* fp;
    fp=fopen ("myfile.bin","rb");
    if (fp == NULL) {
    fprintf(stderr, "Can't open the file");
    exit(1);}

    fseek (fp,0,SEEK\_END);	//
    size=ftell (fp);		//	get the size of the file
    fseek (fp,0,SEEK\_SET);	//
    
    if ((buf=(unsigned char\*) malloc (size+1))==0)
    	printf("\\n%s","allocation Error");
    
    n=fread (buf,sizeof (buf),size,fp);
    printf ("\\n%02x %lu bytes read",buf\[15\],n);
    
    free (buf);
    fclose (fp);
    return 0;
    

    }

    D D S 3 Replies Last reply
    0
    • F Fossi Bluman

      I use the bellow code to read binary file but it throws an exceptions at run time and sometimes gives a wrong results , please tell me what's the wrong ?

      #include
      #include

      unsigned long size,n;
      int main()
      {
      unsigned char *buf;
      FILE* fp;
      fp=fopen ("myfile.bin","rb");
      if (fp == NULL) {
      fprintf(stderr, "Can't open the file");
      exit(1);}

      fseek (fp,0,SEEK\_END);	//
      size=ftell (fp);		//	get the size of the file
      fseek (fp,0,SEEK\_SET);	//
      
      if ((buf=(unsigned char\*) malloc (size+1))==0)
      	printf("\\n%s","allocation Error");
      
      n=fread (buf,sizeof (buf),size,fp);
      printf ("\\n%02x %lu bytes read",buf\[15\],n);
      
      free (buf);
      fclose (fp);
      return 0;
      

      }

      D Offline
      D Offline
      David Crow
      wrote on last edited by
      #2

      Fossi Bluman wrote:

      ...it throws an exceptions at run time...

      What exception? Where?

      n=fread (buf,sizeof (buf),size,fp);
      printf ("\n%02x %lu bytes read",buf[15],size);

      I can tell you right now that these two lines will raise eyebrows. Among other things, size is the number of bytes to read, whereas n is the number of bytes actually read.

      "One man's wage rise is another man's price increase." - Harold Wilson

      "Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons

      "You can easily judge the character of a man by how he treats those who can do nothing for him." - James D. Miles

      K 1 Reply Last reply
      0
      • F Fossi Bluman

        I use the bellow code to read binary file but it throws an exceptions at run time and sometimes gives a wrong results , please tell me what's the wrong ?

        #include
        #include

        unsigned long size,n;
        int main()
        {
        unsigned char *buf;
        FILE* fp;
        fp=fopen ("myfile.bin","rb");
        if (fp == NULL) {
        fprintf(stderr, "Can't open the file");
        exit(1);}

        fseek (fp,0,SEEK\_END);	//
        size=ftell (fp);		//	get the size of the file
        fseek (fp,0,SEEK\_SET);	//
        
        if ((buf=(unsigned char\*) malloc (size+1))==0)
        	printf("\\n%s","allocation Error");
        
        n=fread (buf,sizeof (buf),size,fp);
        printf ("\\n%02x %lu bytes read",buf\[15\],n);
        
        free (buf);
        fclose (fp);
        return 0;
        

        }

        D Offline
        D Offline
        Daniel Pfeffer
        wrote on last edited by
        #3

        in your fread() statement, you have: sizeof(buf) - the size of the pointer, at least 2 (on 16-bit processors), but typically 4 (32-bit) or 8 (64-bit) bytes these days. size - size of file in characters (each character is defined to be 1 unit in size) You are reading at least twice (four times / eight times) the data that you expected, overflowing the buffer. Perhaps you meant to write: n = fread(buf, sizeof(*buf), size, fp); As another poster mentioned, your printf() statement also looks funny.

        If you have an important point to make, don't try to be subtle or clever. Use a pile driver. Hit the point once. Then come back and hit it again. Then hit it a third time - a tremendous whack. --Winston Churchill

        F 1 Reply Last reply
        0
        • D Daniel Pfeffer

          in your fread() statement, you have: sizeof(buf) - the size of the pointer, at least 2 (on 16-bit processors), but typically 4 (32-bit) or 8 (64-bit) bytes these days. size - size of file in characters (each character is defined to be 1 unit in size) You are reading at least twice (four times / eight times) the data that you expected, overflowing the buffer. Perhaps you meant to write: n = fread(buf, sizeof(*buf), size, fp); As another poster mentioned, your printf() statement also looks funny.

          If you have an important point to make, don't try to be subtle or clever. Use a pile driver. Hit the point once. Then come back and hit it again. Then hit it a third time - a tremendous whack. --Winston Churchill

          F Offline
          F Offline
          Fossi Bluman
          wrote on last edited by
          #4

          this funny "fread" doing the job , exactly as i need , any way ,, how to make it not funny ?

          D 1 Reply Last reply
          0
          • F Fossi Bluman

            this funny "fread" doing the job , exactly as i need , any way ,, how to make it not funny ?

            D Offline
            D Offline
            Daniel Pfeffer
            wrote on last edited by
            #5

            Examine the printf() statement closely. You will see the following formatting: %02x for buf[15] %lu for size The %02x formatting is meant for printing an unsigned int, but you are printing an unsigned char. In order to be certain that this works on all systems, cast buf[15] to unsigned int.

            If you have an important point to make, don't try to be subtle or clever. Use a pile driver. Hit the point once. Then come back and hit it again. Then hit it a third time - a tremendous whack. --Winston Churchill

            F 1 Reply Last reply
            0
            • D Daniel Pfeffer

              Examine the printf() statement closely. You will see the following formatting: %02x for buf[15] %lu for size The %02x formatting is meant for printing an unsigned int, but you are printing an unsigned char. In order to be certain that this works on all systems, cast buf[15] to unsigned int.

              If you have an important point to make, don't try to be subtle or clever. Use a pile driver. Hit the point once. Then come back and hit it again. Then hit it a third time - a tremendous whack. --Winston Churchill

              F Offline
              F Offline
              Fossi Bluman
              wrote on last edited by
              #6

              then how to print the hexadecimal values in a format of two digits ?

              1 Reply Last reply
              0
              • D David Crow

                Fossi Bluman wrote:

                ...it throws an exceptions at run time...

                What exception? Where?

                n=fread (buf,sizeof (buf),size,fp);
                printf ("\n%02x %lu bytes read",buf[15],size);

                I can tell you right now that these two lines will raise eyebrows. Among other things, size is the number of bytes to read, whereas n is the number of bytes actually read.

                "One man's wage rise is another man's price increase." - Harold Wilson

                "Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons

                "You can easily judge the character of a man by how he treats those who can do nothing for him." - James D. Miles

                K Offline
                K Offline
                k5054
                wrote on last edited by
                #7

                DavidCrow wrote:

                Among other things, size is the number of bytes to read, whereas n is the number of bytes actually read.

                Just to clarify - the signature of fread() is

                size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);

                where size is the size of each data element and nmemb is the number of elements read. The returned value is the number of data elements actually read. Thus

                FILE *f;
                struct mystruct foo[10];
                size_t n;
                n = fread(foo, sizeof(struct mystruct), 10, f);

                after the call to fread(), n will contain the number of (struct mystruct) items read, not the number of bytes read. So if sizeof(struct mystruct) = 42 and the stream f contains 4 items between the current file pointer and the end of file, then fread() will return 4 (the number of items), not 168 (the number of bytes [42*4]).

                D 1 Reply Last reply
                0
                • K k5054

                  DavidCrow wrote:

                  Among other things, size is the number of bytes to read, whereas n is the number of bytes actually read.

                  Just to clarify - the signature of fread() is

                  size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);

                  where size is the size of each data element and nmemb is the number of elements read. The returned value is the number of data elements actually read. Thus

                  FILE *f;
                  struct mystruct foo[10];
                  size_t n;
                  n = fread(foo, sizeof(struct mystruct), 10, f);

                  after the call to fread(), n will contain the number of (struct mystruct) items read, not the number of bytes read. So if sizeof(struct mystruct) = 42 and the stream f contains 4 items between the current file pointer and the end of file, then fread() will return 4 (the number of items), not 168 (the number of bytes [42*4]).

                  D Offline
                  D Offline
                  David Crow
                  wrote on last edited by
                  #8

                  All true, but that doesn't change the issue that the OP is having. I was simply hinting at the fact that size and n may differ, and the parameter being sent to printf() was incorrect.

                  "One man's wage rise is another man's price increase." - Harold Wilson

                  "Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons

                  "You can easily judge the character of a man by how he treats those who can do nothing for him." - James D. Miles

                  1 Reply Last reply
                  0
                  • F Fossi Bluman

                    I use the bellow code to read binary file but it throws an exceptions at run time and sometimes gives a wrong results , please tell me what's the wrong ?

                    #include
                    #include

                    unsigned long size,n;
                    int main()
                    {
                    unsigned char *buf;
                    FILE* fp;
                    fp=fopen ("myfile.bin","rb");
                    if (fp == NULL) {
                    fprintf(stderr, "Can't open the file");
                    exit(1);}

                    fseek (fp,0,SEEK\_END);	//
                    size=ftell (fp);		//	get the size of the file
                    fseek (fp,0,SEEK\_SET);	//
                    
                    if ((buf=(unsigned char\*) malloc (size+1))==0)
                    	printf("\\n%s","allocation Error");
                    
                    n=fread (buf,sizeof (buf),size,fp);
                    printf ("\\n%02x %lu bytes read",buf\[15\],n);
                    
                    free (buf);
                    fclose (fp);
                    return 0;
                    

                    }

                    S Offline
                    S Offline
                    Software_Developer
                    wrote on last edited by
                    #9

                    Hello. Here is another solution.

                    //******************************************
                    // reading an entire binary file the c++ way

                    #include #include using namespace std;

                    int main (){

                    streampos size;
                    char * memblock;
                    cout<<" \n\n";

                    // open file as binary
                    ifstream file ("myfile.bin", ios::in|ios::binary|ios::ate);
                    if ( file.is_open() ){

                    // get file size
                    size = file.tellg();
                    
                    // alloocate appropiate file size + 1 for '\\0'
                    memblock = new char \[size+1\];
                    
                    // go to begining of file
                    file.seekg (0, ios::beg);
                    
                    // read entire file into ram memory
                    file.read (memblock, size);
                    file.close();
                    
                    // display size of file
                    cout << "the entire file content of "<< size <<" bytes is in memory  \\n\\n\\n";
                    
                    // release memory
                    delete\[\] memblock;
                    

                    }
                    else cout << "Unable to open file\n\n";

                    cout<<"Press ANY key to close.\n\n";
                    cin.ignore(); cin.get();
                    return 0;
                    }

                    F 1 Reply Last reply
                    0
                    • S Software_Developer

                      Hello. Here is another solution.

                      //******************************************
                      // reading an entire binary file the c++ way

                      #include #include using namespace std;

                      int main (){

                      streampos size;
                      char * memblock;
                      cout<<" \n\n";

                      // open file as binary
                      ifstream file ("myfile.bin", ios::in|ios::binary|ios::ate);
                      if ( file.is_open() ){

                      // get file size
                      size = file.tellg();
                      
                      // alloocate appropiate file size + 1 for '\\0'
                      memblock = new char \[size+1\];
                      
                      // go to begining of file
                      file.seekg (0, ios::beg);
                      
                      // read entire file into ram memory
                      file.read (memblock, size);
                      file.close();
                      
                      // display size of file
                      cout << "the entire file content of "<< size <<" bytes is in memory  \\n\\n\\n";
                      
                      // release memory
                      delete\[\] memblock;
                      

                      }
                      else cout << "Unable to open file\n\n";

                      cout<<"Press ANY key to close.\n\n";
                      cin.ignore(); cin.get();
                      return 0;
                      }

                      F Offline
                      F Offline
                      Fossi Bluman
                      wrote on last edited by
                      #10

                      thank you for reply , but I use C language .

                      1 Reply Last reply
                      0
                      Reply
                      • Reply as topic
                      Log in to reply
                      • Oldest to Newest
                      • Newest to Oldest
                      • Most Votes


                      • Login

                      • Don't have an account? Register

                      • Login or register to search.
                      • First post
                        Last post
                      0
                      • Categories
                      • Recent
                      • Tags
                      • Popular
                      • World
                      • Users
                      • Groups