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 with the rest.
Here's the code I've got for reading the file so far:
#include "stdafx.h"
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream myReadFile;
myReadFile.open("text.txt");
char output[500];
int found;
int line;
if (myReadFile.is_open()) {
line = 0;
while (!myReadFile.eof()) {
myReadFile >> output;
if(line > 20) {
cout << output;
}
line++;
}
}
myReadFile.close();
system("PAUSE");
return 0;
}
Many thanks in advance.
First of all, your while
loop is wrong. In fact, such while
loop is almost always wrong.
You should be writing the loop as:
while (myReadFile >> output)
{
if (line > 20) {
cout << output;
}
line++;
}
Your while(!myReadFile.eof())
loop is wrong, because the eof
flag (or any other failure flag) is set after an attempt to read from the stream fails; that means, if the attempt to read fails, you're still outputting, because you're still inside the loop, and the rest of the code in the loop still executes when it in fact should not.
In my version, however, if an attempt to read (i.e myReadFile >> output
) fails, then returned std::istream&
implicitly converts into false
, and the loop exits immediately. And if it doesn't fail, the returned stream implicitly converts to true
.
By the way, it seems to me that you want to read line-by-line, instead of word-by-word. If so, then you should write this as:
std::string sline; //this should be std::string
while (std::getline(myReadFile, sline))
{
if (line > 20) {
cout << sline;
}
line++;
}
Again std::getline
returns std::istream
. If the read was successful, the returned stream implicitly converts to true
and the loop will continue, or if it was unsuccessful, then it would implicitly convert to false
and the loop will exit.
std::string file_contents = LoadFileAsString("text.txt");
std::string::size_type offset = file_contents.find("<--START-->");
std::ofstream("text.txt") << file_contents.c_str() + offset;
With LoadFileAsString defined like this:
std::string LoadFileAsString(const std::string & fn)
{
std::ifstream fin(fn.c_str());
if(!fin)
{
std::string what = "LoadFileAsString() : Failed to open file \"";
what += fn + '\"';
throw std::runtime_error(what);
}
std::ostringstream oss;
oss << fin.rdbuf();
return oss.str();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With