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";
#include <fstream>
#include <limits>
bool writeToFile( charconst* filename, unsigned lineNo, charconst * toWrite)
{
std::fstream file( filename ) ;
if ( !file )
returnfalse ;
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.