GIDForums  

Go Back   GIDForums > Computer Programming Forums > C++ Forum
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 30-Apr-2009, 08:29
nanchuangyeyu nanchuangyeyu is offline
New Member
 
Join Date: Apr 2009
Posts: 15
nanchuangyeyu has a little shameless behaviour in the past
Question

Questions about reading binary file into unsigned int arrays.


Hello,
I am trying to read a binary file into an 2D unsigned int array.But the C++ .read() file i/o operation seems to work on char arrays only.Any one can show me an efficient solution?Thank u in advance.
Lixiang
  #2  
Old 30-Apr-2009, 09:48
fakepoo fakepoo is offline
Regular Member
 
Join Date: Oct 2007
Posts: 713
fakepoo is a jewel in the roughfakepoo is a jewel in the roughfakepoo is a jewel in the rough

Re: Questions about reading binary file into unsigned int arrays.


Is that the ifstream::read method?

Just cast the unsigned int* to a char* before passing it into the method. Also make sure that you convert the size for allocating the array. The following is the example from the link (above) changed to read an unsigned int array:
CPP / C++ / C Code:
// read a file into memory
#include <iostream>
#include <fstream>
using namespace std;

int main () {
  int length;
  unsigned int* buffer;

  ifstream is;
  is.open ("test.txt", ios::binary );

  // get length of file:
  is.seekg (0, ios::end);
  length = is.tellg();
  is.seekg (0, ios::beg);

  // allocate memory:
  buffer = new unsigned int[length * sizeof(char) / sizeof(unsigned int)];

  // read data as a block:
  is.read ((char*)buffer,length);
  is.close();

  cout.write ((char*)buffer,length);

  delete[] buffer;
  return 0;
}
  #3  
Old 30-Apr-2009, 09:57
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 5,218
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold

Re: Questions about reading binary file into unsigned int arrays.


Quote:
Originally Posted by nanchuangyeyu
.the C++ .read() file i/o operation seems to work on char arrays ...

The fstream read and write functions take an argument that is a pointer to char.

If you want to write an integer, then you can cast the address of the int as a pointer to char.

If you want to read an integer, then you can cast the address of the int as a pointer to char.

When investigating things like this, I always like to start with a small file whose contents are known. In other words, I will create a binary file with a couple of integers then read it back.

Now, since it is possible that you don't know for sure how to create a small binary file with known contents, I'll show a program that does exactly that:

CPP / C++ / C Code:
//
// Write a couple of integers to a binary file
//
// davekw7x
//
#include <iostream>
#include <iomanip>
#include <fstream>

using namespace std;

int main()
{
    char *filename = "test.bin";
    ofstream outfile(filename, ios::binary);
    if (!outfile) {
        cerr << "Can't open file " << filename << " for writing." << endl;
        exit(EXIT_FAILURE);
    }
    cout << "Opened binary file " << filename << " for writing." << endl;
    unsigned int i;

    i = 0x12340a78;
    cout << "writing " << setw(11) << i << endl;
    outfile.write(reinterpret_cast<char *>(&i), sizeof(i));

    i = 0xcd0abef1;
    cout << "writing " << setw(11)<<  i << endl;
    outfile.write(reinterpret_cast<char *>(&i), sizeof(i));

    outfile.close();

    return 0;
}

Output on my Linux system:
Code:
Opened binary file test.bin for writing. writing 305400440 writing 3440033521

The size of the file "test.bin" created by this program on my system is 8. See Footnote.


If this program runs successfully, you can try the following read the integers from the file. I used a vector of ints. You can use an array if you are careful not to read more than the size of the array.

CPP / C++ / C Code:
//
// Read ints from a binary file into a vector.
//
// This assumes that the size and endianness of the binary
// values are compatible this machine.
//
// davekw7x
//
#include <iostream>
#include <iomanip>
#include <fstream>
#include <vector>

using namespace std;

int main()
{
    unsigned int i;
    vector<unsigned int> ivector;
    char *filename = "test.bin";
    ifstream infile(filename,ios::binary);
    if (!infile) {
        cerr << "Can't open file " << filename << " for reading" << endl;
        exit(EXIT_FAILURE);
    }
    cout << "Opened binary file " << filename << " for reading." << endl;
    while (infile.read(reinterpret_cast<char *>(&i), sizeof(i))) {
        ivector.push_back(i);
    }

    for (unsigned count  = 0; count < ivector.size(); count++) {
        cout << "ivector[" << count << "] = " 
             << setw(11) << ivector[count] << endl;
    }

    infile.close();

    return 0;
}

Output:
Code:
Opened binary file test.bin for reading. ivector[0] = 305400440 ivector[1] = 3440033521
Regards,

Dave

Footnote:
Since I wrote two ints, I conclude that the size of an int is 4. Of course I could have just printed the size of an int by something like the following to find out what the size of an int is with my compiler:
CPP / C++ / C Code:
    cout << "sizeof(int) = " << sizeof(int) << endl;

Note that the C and C++ standards documents specifically do not guarantee that the size of an int is always going to be 4, but that seems to be the case for any reasonably current compiler that you are likely to run across for personal workstations these days.

If you are using an ancient compiler that has 16-bit ints, then sizeof(int) will be equal to 2. If sizeof(int) is equal to 2, I strongly recommend that people upgrade their compilers to something more current.

Not just because of the size of ints (although that might be reason enough), but because old compilers with non-standard features and functions sometimes encourage beginners to get into bad habits and the old compilers lack many standard features that beginners should be learning.
  #4  
Old 30-Apr-2009, 10:07
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 5,218
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold

Re: Questions about reading binary file into unsigned int arrays.


Quote:
Originally Posted by fakepoo
...
CPP / C++ / C Code:
...
  cout.write ((char*)buffer,length);
...

I was with you up to there. I'm thinking that writing the char equivalents of the bytes of an int is not very illuminating.


If I wanted to see the integer values in the array in your program after reading them in, I might do something like:
CPP / C++ / C Code:
  int count = length / sizeof(int);
  cout << "Number of ints = " << count << endl;
  for (int i = 0; i < count; i++) {
      cout << "buffer[" << i << "] = " << buffer[i] << endl;
  }

I particularly appreciate seeing how to determine the size of a file with seekg/tellg. It also shows why C++ programmers usually use vectors instead of arrays, since with vectors it's not necessary to know the size of the file before starting to read.

This part (knowing the size) is even more problematic for "2D arrays" if they have to be allocated dynamically. Whether it's a 2D array or a vector of vectors, we would probably end up reading one int at a time, or maybe a row at a time.

Regards,

Dave
  #5  
Old 30-Apr-2009, 10:10
fakepoo fakepoo is offline
Regular Member
 
Join Date: Oct 2007
Posts: 713
fakepoo is a jewel in the roughfakepoo is a jewel in the roughfakepoo is a jewel in the rough

Re: Questions about reading binary file into unsigned int arrays.


Quote:
Originally Posted by davekw7x
I was with you up to there...
I agree with you on this.
 
 

Recent GIDBlogAccepted for Ph.D. program by crystalattice

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Power Calibration Error In Nero Fix (hopefully) matt3678 Computer Hardware Forum 60 20-Aug-2009 06:04
contents of .txt file into 2D array anirudhroxrulz C Programming Language 4 10-Apr-2008 23:45
Airport Log program using 3D linked List : problem reading from file batrsau C Programming Language 11 29-Feb-2008 08:44
After execution - Error cannot locate /Skin File? WSCH C++ Forum 1 05-Mar-2005 21:03
fltk-2.0 cvs Plumb FLTK Forum 20 13-Nov-2004 08:10

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 21:22.


vBulletin, Copyright © 2000 - 2009, Jelsoft Enterprises Ltd.