I surprise why not get error.

Started by
5 comments, last by desertcube 18 years, 10 months ago

#include <fstream>
#include <vector>
#include <iostream> 
#include <windows.h>
 
main()
{	
 	std::ifstream infile("coast.raw", std::ios_base::binary) ;
	std::vector<BYTE> in (14096);
	infile.read((char*)&in[0], in.size());
	for (int i=0;i<in.size();i++)
	std::cout<<(int)in<<" ";
  
}

and the coast.raw just have 4096 pixel,but I read 14096.so why the read() not give a error instead of fill 0 for inexistence data.
Advertisement
Maybe you are just reading past that file and just whatever is on the harddisk after it. Though I'm not certain as I've never tried to do that.
____________________________________________________________Programmers Resource Central
What makes you think that it actually reads that many bytes? You do not check for the number of read bytes. The size of the vector IS 14096 after all. It is declared thusly, and is not changed by a read operation.
You get an error. Try adding:
if (infile.fail ()){    std::cout << "Failed!";}

and you'll see.

But the error is non-fatal, so it doesn't crash.
Kippesoep
Quote:Original post by Kippesoep
You get an error. Try adding:
*** Source Snippet Removed ***
and you'll see.

But the error is non-fatal, so it doesn't crash.


the if(!infile){...} the same as the if(infile.fail()){...}?
Read does give you an error. You're just not checking for it. Read the other replies again. Furthermore infile is an std::ifstream and hence cannot be used for null checks. And certainly, even if infile was a pointer, it would not be set to null when the read goes beyond eof.
Quote:Original post by tomlu709
Read does give you an error. You're just not checking for it. Read the other replies again. Furthermore infile is an std::ifstream and hence cannot be used for null checks. And certainly, even if infile was a pointer, it would not be set to null when the read goes beyond eof.


Actually, std::basic_ios defines operator!, which returns whether the stream is bad or not.

This topic is closed to new replies.

Advertisement