• Advertisement
Sign in to follow this  

Reading bytes in C++

This topic is 4728 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I admit it, I'm a C programmer trying to do C++. At the moment, I am trying to read a file in to memory. I have a buffer of char's that I'm reading chunks of the file into and processing bit by bit. In C, I'd use fread, which returns the number of bytes read (which I need to know). In C++, I'm doing this:
  while (fileStream.good() && bytesRead > 0) {
    bytesRead = fileStream.readsome(buffer, bufferSize);
  }

It seems that readsome will succeed and never hit eof, it will only return that 0 bytes were read. If I use fileStream.read, that hits eof but doesn't return the number of bytes read back to me. Is this a decent way to go, or am I just way out of wack here?

Share this post


Link to post
Share on other sites
Advertisement
If you use .read() you can so something like this using tellg():

ifstream IF;
...
IF.open("blah.txt");
...
int start = IF.tellg();
IF.read( ... );
int readbytes = IF.tellg() - start;


OR


char buffer[1024];
memset(buffer,0,1024);
IF.read(buffer,1024);
int readbytes = strlen(buffer);


A few ideas. I think the first would work the best though. Here is a reference on readsome(). I don't know wht your EOF is never hit, but that has an example that should work.

Share this post


Link to post
Share on other sites
readsome() only grabs what data is immediately available in the stream buffer, unlike read() which will fetch some more from the file if necessary. You will have to manually call sync() to force the data fetch and replenish the buffer.

Share this post


Link to post
Share on other sites
You can read with ifstream::read() and get the number of characters read with ifstream::gcount.

This will load a file into a char buffer.


std::ifstream ifs("test.txt", std::ios::binary);
if(!ifs)
//error

ifs.seekg(0, std::ios::end);
int filesize = ifs.tellg();
ifs.seekg(0, std::ios::beg);

char* buffer = 0;

if( filesize < 10000000 ) // make sure file < 10 megs
{
buffer = new char[filesize];
ifs.read(buffer, filesize);
assert(ifs.gcount() == filesize);
}

// edit: one bug fixed

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement