Read 4 bytes at a time

I have a large file full of integers that I upload. I just started using C ++, and I'm trying to use material for filtering. From everything that I read, it seems that I can only read in bytes. So I had to tweak the char array and then use it as an int pointer.

Is there a way that I can read 4 bytes at a time and eliminate the need for a char array?

const int HRSIZE = 129951336;  //The size of the table
char bhr[HRSIZE];   //The table
int *dwhr;

int main()
{
    ifstream fstr;

    /* load the handranks.dat file */
    std::cout << "Loading table.dat...\n";
    fstr.open("table.dat");
    fstr.read(bhr, HRSIZE);
    fstr.close();
    dwhr = (int *) bhr;    
}
+5
source share
5 answers

To read a single integer, go to the integer address of the read function and make sure you only read sizeof intbytes.

int myint;

//...

fstr.read(reinterpret_cast<char*>(&myint), sizeof(int));

You may also need to open the file in binary mode.

fstr.open("table.dat", std::ios::binary);
+14
source

4 ifstream, operator>> ( basic_istream, istream_iterator operator>> . basic_ifstream , ):

#include <fstream>

typedef unsigned int uint32_t;    
struct uint32_helper_t {};

namespace std {
template<class traits>
class basic_istream<uint32_helper_t, traits> : public basic_ifstream<uint32_t> {
public:
    explicit basic_istream<uint32_helper_t, traits>(const char* filename, 
        ios_base::openmode mode ) : basic_ifstream<uint32_t>( filename, mode ) {}

    basic_istream<uint32_helper_t, traits>& operator>>(uint32_t& data) {
        read(&data, 1);
        return *this;
    }
};
} // namespace std {}

:

std::basic_istream<uint32_helper_t> my_file( FILENAME, std::ios::in|std::ios::binary );
// read one int at a time
uint32_t value;
my_file >> value;

// read all data in file
std::vector<uint32_t> data;
data.assign( std::istream_iterator<uint32_t, uint32_helper_t>(my_file),
  std::istream_iterator<uint32_t, uint32_helper_t>() );
+4

:

int i;
fstr.read((int*)&i, sizeof(int));
+1

, ? , ( ) .

const int HRSIZE = 129951336;  //The size of the table
int dhr[HRSIZE/sizeof(int)];   //The table

int main()
{
    ifstream fstr;

    /* load the handranks.dat file */
    std::cout << "Loading table.dat...\n";
    fstr.open("table.dat");
    fstr.read((char*)dhr, HRSIZE);
    fstr.close();
}
0

:

const int HRSIZE = 129951336/sizeof(int);  //The size of the table
int bhr[HRSIZE];   //The table

int main(int argc, char *argv[])
{
    ifstream fstr;

    /* load the handranks.dat file */
    std::cout << "Loading table.dat...\n";
    fstr.open("table.dat");
    for (int i=0; i<HRSIZE; ++i)
    {
        fstr.read((char *)(bhr+i), sizeof(int));
    }
    fstr.close();

    // for correctness
    return 0;
}
0

All Articles