راهش اینه که کل فایل رو بخونی بازنویسی کنی دوباره بریزی داخل فایل مثلا :
#include <iostream>
#include <fstream>
#include <vector>
void replaceLineFromFile(int index,std::string text,std::string location) throw (const char*)
{
std::fstream file;
// Reading whole file
file.open(location,std::fstream::in);
std::vector <std::string > contents;
std::string temp;
if(file.is_open())
{
while(std::getline(file,temp))
{
contents.push_back(temp);
}
}
else
{
throw "Can not open file";
}
file.close();
//Changing lines
if(index<contents.size())
{
contents[index]=text;
}
else
{
throw "Wrong Index";
}
//Writing again to the file
file.open(location,std::fstream::out);
if(file.is_open())
{
for(std::string i : contents)
file<<i<<"\n";
}
else
{
throw "Can not open file";
}
file.close();
}
int main()
{
try
{
replaceLineFromFile(2,"Some new Text","D:\\a.txt");
}
catch(const char* exc)
{
std::cout<<exc;
}
}