Advertisement Jump to content
Sign in to follow this  
hisDudeness

file manipulation with ifstream

This topic is 4927 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've been searching google for any possible way for a C++ program to actually manipulate a text file with iftsream or some other method. Let's say I had a text file "data.txt" and only wanted to read from certain lines and from certain columns within the file? How could I instruct ifstream to drop down, say, five lines from the beginning of the file? I could use the 'ignore' iftsream member to scan the line for the right information then. How can I permanently delete characters and lines from a text file using these methods?

Share this post


Link to post
Share on other sites
Advertisement
The kinds of things you want to do with a file take a different approach than ifstream. ifstream treats files as a stream of data, which means that you pull things from it as you can, until it's gone. Although it has functions such as putback and seek, the interface wasn't designed with such random access functionality as the primary use. What you may be best off doing is using the stream to read the entire file into your own memory space, then performing your own operations on it. One major difference would be the "lines and columns" and "drop down five lines" functionality that you mentioned -- since the data is stored sequentially on the disk, you have to parse for the line break character before you can perform per-line access.

Share this post


Link to post
Share on other sites
But that's not a real problem you can do something like this:


std::vector< std::string > stringVec;
std::ifstream in( "data.txt" );
std::string tmp;

while( !in.eof() )
{
std::getline( in, tmp );
stringVec.push_back( tmp );
}


note: maybe the parameters of getline are std::getline( tmp, in )

Now you have an array of strings, where each string represents a line from your text file.
To acces the fith line just type "stringVec[ 5 ]". The newline at the end of each line is not in the string (getline removes the newline).


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!