Advertisement Jump to content
Sign in to follow this  

fstream seekg() and read()

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

(Cplusplus) I need to perform "random access" on a data file I am using; meaning that I need to be able to specify any arbitrary place in the file and read data at that point. I am working with a binary file, and so have used ios::binary when opening the file reader. I understand how to use seekg(int, ios_base::seekdir) to move the read marker in conjunction with read(char*,int) to specify how many characters to read at the read marker's location... i'm just getting caught up in some technical details here. Say I have a string of 12 characters, "Hello,world!", that I want to read. Also assume 1-byte characters in accordance with ASCII.
#include <fstream>
#include <string>

// inside of main...
ifstream fin;
string inFile = "test.dat", ios::in | ios::binary);

// Now I want to use seekg() and read() to acquire the substring
// "wor" from "Hello,world!". NOTE: In understand there are easier
// ways of doing this but I want to use seekg/read specifically.
fin.seekg(6, ios_base::beg);*)temp_str, 3);

Would this code result with storing "wor" into temp_str? What is confusing me is this: I am not sure how to "translate" seekg and read. To me, the line fin.seekg(6, ios_base::beg) says "Move the read pointer 6 units to the right of the beginning of the file" (since 'w' is the 7th character). And the line* ... */) says "Beginning with the current character/byte in the file, read 3 characters without moving the read pointer." I can't download a C++ compiler right now and check this out for myself. Please let me know if I am on track or if I am slightly misinformed... -ply

Share this post

Link to post
Share on other sites
You might want to try googleing std:fstream and that may answer your questions on its own. :) check out msdn thats a good resource.

Regards Jouei

Share this post

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

  • Advertisement

Important Information

By using, you agree to our community Guidelines, Terms of Use, and Privacy Policy. 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!