我正在使用Visual C++ Express 2010 ...而且我对C++很新.
我想读取一个文件,然后删除"< - START - >"之前的所有内容,并用其余文件重写该文件.
这是我到目前为止阅读文件的代码:
#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;
}
Run Code Online (Sandbox Code Playgroud)
提前谢谢了.
首先,你的while循环是错误的.事实上,这种while循环几乎总是错误的.
你应该把循环写成:
while (myReadFile >> output)
{
if (line > 20) {
cout << output;
}
line++;
}
Run Code Online (Sandbox Code Playgroud)
你的while(!myReadFile.eof())循环是错误的,因为在尝试从流中读取失败后eof设置了标志(或任何其他失败标志); 这意味着,如果读取尝试失败,您仍然在输出,因为您仍然在循环内部,并且循环中的其余代码仍然执行,而实际上它不应该执行.
但是,在我的版本中,如果尝试读取(即myReadFile >> output)失败,则返回std::istream& 隐式转换为false,并且循环立即退出.如果它没有失败,则返回的流隐式转换为true.
顺便说一句,在我看来,你想要逐行阅读,而不是逐字逐句.如果是这样,那么你应该写为:
std::string sline; //this should be std::string
while (std::getline(myReadFile, sline))
{
if (line > 20) {
cout << sline;
}
line++;
}
Run Code Online (Sandbox Code Playgroud)
再次std::getline回归std::istream.如果读取成功,则返回的流隐式转换为true并且循环将继续,或者如果它不成功,则它将隐式转换为false并且循环将退出.
您无法读取文件,然后删除“<--START-->”一词之前的所有内容,并用其余部分重写该文件,除非在本杰明回答的内存中。否则你需要一个中间文件。在所有情况下,您都应该处理各种错误情况。这应该可以做到:
#include <iostream>
#include <fstream>
#include <string>
#include <cstdio>
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;
}
Run Code Online (Sandbox Code Playgroud)
。