Reputation: 755
I've tried many versions of the following code in g++ ( version 4.6.3 ).
int main(int argc,char *argv[])
{
std::string fname(argv[1]);
std::cout<<"fname is"<<fname<<std::endl;
// std::fstream f(fname.c_str(),
std::fstream::in|std::fstream::out|std::fstream::binary);
std::fstream f(fname.c_str(),std::ios::in|std::ios::out|std::ios::binary);
unsigned char b[512];
memset(b,0xff,512);
std::cout<<f.tellg()<<std::endl;
f.seekg(0,std::ios::beg);
std::cout<<f.tellg()<<std::endl;
f.read((char *)b,512);
for(int ii=0;ii<sizeof(sector0);ii++)
std::cout<<std::hex<<(int )(b[ii]) <<" ";
std::cout<<std::endl;
}
In each case the result is the same I pass in the file name of the source code ( sample ascii ), tellg reports a 1 and the buffer matches the file. If I pass in the filename of the executable ( my sample binary ), tellg reports -1 and the dump is all ff's.
Am I doing something wrong or is this a compiler bug?
Upvotes: 0
Views: 337
Reputation: 6875
Sorry for the short answer, but don't have much time.
You are opening the file for writing (std::ios::out
) which requires an exclusive lock on the file. If the file is already in use, acquiring the lock fails, therefor opening and reading will fail too.
Upvotes: 2