file manipulation with ifstream

Started by
1 comment, last by ext 18 years, 9 months ago
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?
Well I believe in God, and the only thing that scares me is Keyser Soze.
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.
{[JohnE, Chief Architect and Senior Programmer, Twilight Dragon Media{[+++{GCC/MinGW}+++{Code::Blocks IDE}+++{wxWidgets Cross-Platform Native UI Framework}+++
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).


This topic is closed to new replies.

Advertisement