I\'m using Visual C++ Express 2010... and I\'m very new to C++.
I want to read a file then remove everything before the word \"<--START-->\" and rewrite the file
You cannot read a file then remove everything before the word "<--START-->" and rewrite the file with the rest, except in memory as answered by Benjamin. Otherwise you need an intermediate file. In all cases you should handle various error conditions. This should do it:
#include
#include
#include
#include
using namespace std;
int main()
{
if (rename("Text.txt", "Old.txt") == 0)
{
try
{
ifstream in("Old.txt");
ofstream out("Text.txt");
string line;
while (getline(in, line))
{
size_t pos = line.find("<--START-->");
if (pos != string::npos)
{
string remain = line.substr(pos + 11);
if (remain.size())
out << remain << endl;
break;
}
}
while (getline(in, line))
out << line << endl;
}
catch (exception&)
{
remove("Text.txt");
rename("Old.txt", "Text.txt");
cerr << "Error processing file" << endl;
return 1;
}
remove("Old.txt");
return 0;
}
cerr << "Error renaming file, access right?" << endl;
return 2;
}
.