Write to specific Text Line

Well a while back i was making a text based gamed in C++ its coming alone whell. But i have a questions. I want to write to line nine of a text file just putting a letter there. I get the name of the file like this
filename = "C:/Users/Tim/Desktop/Folder/Documents/Programing/C++/New Folder/Items/" + itemlook + ".txt";
?
Can u elaborate ur problem with code snippet.
? ALl i want to do is use a variable as the filename and get lets say line 10 and change its text.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <fstream>
#include <limits>

bool writeToFile( char const* filename, unsigned lineNo, char const * toWrite)
{
     std::fstream file( filename ) ;
     if ( !file )
          return false ;

     unsigned currentLine = 0 ;
     while ( currentLine < lineNo )
     {
          // We don't actually care about the lines we're reading,
          // so just discard them.
          file.ignore( std::numeric_limits<std::streamsize>::max(), '\n') ;
          ++currentLine ;
     }

     // Position the put pointer -- switching from reading to writing.
     file.seekp(file.tellg()) ;

     return file << toWrite ;   
}


Caveats: This can't replace a string that is larger or smaller than already exists in the file. You could fudge it if the string in the file is larger by padding "toWrite" with spaces at the end to match the length of the string in the file. If the string in the file is smaller than that in "toWrite" you're going to overwrite something you didn't intend to.

Also, this assumes the first line in the file is line 0. You'll have to make an adjustment if you wish to refer to the first line as line 1.




Last edited on
Topic archived. No new replies allowed.