2
votes

Trying to read from a file 4 bytes at a time and I can't figure out exactly how to adjust the parameters of ifstream.read() to get it working.

(As a side note: the file ("dummy.txt") is simply a dummy file created through Windows command line "fsutil.exe", so there aren't any actual integers in the file.)

//Benchmark Program in C++
#include <iostream>
#include <fstream>
#include <time.h>
using namespace std;

int main() {
    clock_t t1,t2;
    t1=clock();
    int temp;
    int myint;
    ifstream fstr;
    fstream dummy("dummy.txt", ios::binary);
    while(!dummy.eof()) {
        temp = fstr.read(reinterpret_cast<char*>(&myint), sizeof(int));
    }
    cout << "Hard Drive Benchmark"
         << endl;
    t2=clock();
    float diff ((float)t2-(float)t1);
    float seconds = diff / CLOCKS_PER_SEC;
    cout << "Time Taken: " << seconds << " seconds" <<endl;
}

The errors I receive are:

C:\Users\Tai\Desktop\File-Benchmark.cpp||In function 'int main()':| C:\Users\Tai\Desktop\File-Benchmark.cpp|15| error: invalid user-defined conversion from 'std::basic_istream::__istream_type {aka std::basic_istream}' to 'int' [-fpermissive]| c:\program files (x86)\codeblocks\mingw\lib\gcc\mingw32\4.8.1\include\c++\bits\basic_ios.h|115|

note: candidate is: std::basic_ios<_CharT, _Traits>::operator void*() const [with _CharT = char; _Traits = std::char_traits] | c:\program files (x86)\codeblocks\mingw\lib\gcc\mingw32\4.8.1\include\c++\bits\basic_ios.h|115|

note: no known conversion for implicit 'this' parameter from 'void*' to 'int'| ||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

1
does your code work? If not what goes wrong? - pm100
@pm100 it does not - I get a few compile errors, I'll add them to the post. - secondubly
i would use fread - that feels like the right kind of thing for byte fiddling - pm100
fstr.read returns the stream not an int cplusplus.com/reference/istream/istream/read - pm100
@doc: Pure and simply, it is named badly. ios::binary actually means "disable newline translation", nothing more. - Ben Voigt

1 Answers

4
votes

I'd write the loop like so:

uint32_t myint;
while(fstr.read(reinterpret_cast<char*>(&myint), sizeof(myint))) {
    // do something with myint
}
  • Use sizeof on the actual object (minimize chances of getting it wrong)
  • be aware of architectural differences (http://en.wikipedia.org/wiki/Endianness)
  • The eof check is rarely useful. It's only useful after an error has been detected (to figure out whether a specific extraction failed - so you can try something else - or the stream's end was reached)

  • The contextual converion to boolean of the stream object is intended for easy error diagnostics