-
Reading in a binary file
Hey guys,
I'm having a problem reading in a binary file.
Here's my snippet of code I'm trying to work with
Code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
static unsigned short read_array[25198325];
int main()
{
//Tag directory of file
const char *file1 = "/home/my_name/programs/InputFile.ima";
//Set input file reading
fstream reader(file1, ios::in | ios::binary);
if (!reader)
{
cout << "\nFile doesn't exist\n" << endl;
return 0;
}
//char ch;
istream &read(read_array, 25198320);
//reader.read(read_array, 25198320);
return 0;
}
I'm trying to get help out of some books and some online help sites, but haven't gotten anywhere with those.
(i.e. I have no idea what I'm doing :p )
So, I'm trying to just read in data from a 50 MB binary file, and to store all the data in the array before I do anything else.
I get this with the code above
error: invalid initialization of non-const reference of
type 'std::istream&' from a temporary of type 'int'
I've tried to change the array to type char, but that hasn't worked either. It really doesn't like that istream &read line. Other than that, the file initialization part seems fine.
Anyone have any ideas? That would help alot :)
Thanks,
Bri Rock
-
Code:
istream &read(read_array, 25198320);
I don't like the looks of that! You already have a fstream object right? Well use that to read.
-
> //reader.read(read_array, 25198320);
Try this:
reader.read(reinterpret_cast<char *> (read_array), 25198320);
Or:
reader.read(reinterpret_cast<char *> (read_array), sizeof(read_array));
Also, you can use gcount() to find out how many bytes were read:
cout << "bytes read: " << reader.gcount() << endl;
EDIT: Changed static_cast to reinterpret_cast. I have no idea what the differences are between static_cast, reinterpret_cast, and dynamic_cast. Except dynamic_cast occurs at runtime perhaps? :confused:
-
>>50 MB binary file,
>>and to store all the data in the array
That's a fair sized amount of data to read in one go. You'd do better by reading chunks at a time, imho.
Code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
static unsigned char read_array[25198325];
int main(void)
{
const char *file1 = "junk1.cpp";
fstream reader(file1, ios::in | ios::binary);
if (!reader)
{
cout << "\nFile doesn't exist\n" << endl;
return(0);
}
reader.read(read_array, 25198320);
cout << read_array;
reader.close();
return(0);
}