Jump to content
Site Stability Read more... ×
  • Advertisement
Sign in to follow this  

seekg not working with sizeof directly

This topic is 2837 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

This new code paste thingy is pretty annoying.. I have to format it everytime I paste from visual studio.. any chance thats being fixed?

Anyways.. I have some trouble understanding some code.. I get the below to compile, but when I run it the outval is 42, but inval is some garbage value.. now if I swap the seekg line with the commented out lines it works.. why is that? I dont see why this is a difference?

#include <fstream>
#include <iostream>

int main()
int outval = 42;
std::ofstream fileout("test.dat");
fileout.write(reinterpret_cast<char*>(&outval), sizeof(int));
std::cout << outval << std::endl;

int inval;
std::ifstream filein("test.dat");
//int sizeofInt = sizeof(int);
//filein.seekg(-sizeofInt, std::ios::end);
filein.seekg(-sizeof(int), std::ios::end);
filein.read(reinterpret_cast<char*>(&inval), sizeof(int));
std::cout << inval << std::endl;

Share this post

Link to post
Share on other sites
Try this:

filein.seekg(-static_cast<int>(sizeof(int)), std::ios::end);

Directly negating an unsigned should actually cause a compiler warning IIRC (try cranking up your warnings to max, and always treat warnings as errors). Either way, it's going to get you unexpected behavior. Explicitly transitioning through a signed int along the way should fix it.

Share this post

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

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!