Thread: Noob Q: How to read a value of a byte in binary?

  1. #1
    Registered User
    Join Date
    Jun 2009
    Posts
    11

    Noob Q: How to read a value of a byte in binary?

    Hi Everyone, I'm a noob a programming and I've been desperately trying to read a single byte of a file in binary. But whenever I look online all I can find is.

    Code:
    #include <iostream>
    #include <fstream>
    using namespace std;
    
    ifstream::pos_type size;
    char * memblock;
    
    int main () {
      ifstream file ("example.bin", ios::in|ios::binary|ios::ate);
      if (file.is_open())
      {
        size = file.tellg();
        memblock = new char [size];
        file.seekg (0, ios::beg);
        file.read (memblock, size);
        file.close();
    
        cout << "the complete file content is in memory";
    
        delete[] memblock;
      }
      else cout << "Unable to open file";
      return 0;
    }
    I get that and how it can be used with write() to copy a file, but what I need is to read the value of a, specific byte and maybe copy it to an array or int. How do I do that?

    Please help.

  2. #2
    Registered User valaris's Avatar
    Join Date
    Jun 2008
    Location
    RING 0
    Posts
    507
    Code:
    char c;
    file.read (&c, sizeof(char));
    Of course you may want to seek to the proper byte position that you wish to read first.

  3. #3
    Registered User
    Join Date
    Jun 2009
    Posts
    11
    Thanks Valaris! I think I can use this.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Turning Byte into Binary
    By Lang in forum C Programming
    Replies: 8
    Last Post: 09-06-2008, 10:31 AM
  2. Replies: 12
    Last Post: 05-29-2008, 11:36 AM
  3. Assembly Tutorials
    By JoshR in forum A Brief History of Cprogramming.com
    Replies: 13
    Last Post: 06-11-2005, 09:56 AM
  4. Read a binary file
    By Sue Paterniti in forum C Programming
    Replies: 8
    Last Post: 04-29-2002, 02:36 AM
  5. read records fron file into a binary tree
    By Kirsten in forum C Programming
    Replies: 1
    Last Post: 04-23-2002, 02:48 PM