C++ fstream是用c+编辑文本文件的正确方法吗+;?
我想编辑一个包含多行的文本文件。在每一行中,如果第一个字符是空格,我想删除它 我发现了多个ifstream和ofstream的例子。但在这里,输入和输出文件是不同的文件 但我希望输入和输出是同一个文件,但我不知道fstream是否以及如何工作C++ fstream是用c+编辑文本文件的正确方法吗+;?,c++,C++,我想编辑一个包含多行的文本文件。在每一行中,如果第一个字符是空格,我想删除它 我发现了多个ifstream和ofstream的例子。但在这里,输入和输出文件是不同的文件 但我希望输入和输出是同一个文件,但我不知道fstream是否以及如何工作 fstream file; file.open(path, ios::in | ios::out); while (getline(file, line)) { if (line[0] == '
fstream file;
file.open(path, ios::in | ios::out);
while (getline(file, line))
{
if (line[0] == ' ')
{
line.erase(0, 1);
}
file << line << "\n";
}
fstream文件;
打开(路径,ios::in | ios::out);
while(getline(文件,行))
{
如果(第[0]行=“”)
{
行。擦除(0,1);
}
文件您可以使用两个文件执行此操作:
// TODO: error checking!
fstream file1;
file1.open(path1, ios::in);
fstream file2;
file2.open(path2, ios::out | ios::trunc);
while (getline(file1, line))
{
if ( !line.empty() && line[0] == ' ' )
file2 << line.substr( 1 ) << "\n";
else
file2 << line << "\n";
}
file2.close();
file1.close();
到目前为止,代码没有改变我文件中的任何内容
您的问题是您正在修改该行(我认为它只是一个字符串),但没有将其写回文件中谢谢您的帮助!我已按照vu1p3n0x的建议将所有内容保存在向量中。此外,我还删除了名称空间(以防万一)我也会在未来的课程中这样做。多亏了tambre,我从来没有这么想过
我认为代码还远远不够完美,但在这里它是以防有人需要它
std::ifstream filein;
std::string line;
filein.open(help);
std::vector<std::string> temp;
while (std::getline(filein, line))
{
if (!line.empty())
{
if (line[0] == ' ')
{
line.erase(0, 1);
}
}
temp.push_back(line);
}
filein.close();
std::ofstream fileout;
fileout.open(help, std::ofstream::out, std::ofstream::trunc);
int l = 0;
while (l < temp.size())
{
//cout << temp[l] << "\n";
fileout << temp[l] << "\n";
l++;
}
fileout.close();
std::ifstream filein;
std::字符串行;
filein.open(帮助);
std::向量温度;
while(std::getline(filein,line))
{
如果(!line.empty())
{
如果(第[0]行=“”)
{
行。擦除(0,1);
}
}
温度推回(线路);
}
filein.close();
std::流文件输出;
open(帮助,std::ofstream::out,std::ofstream::trunc);
int l=0;
而(l //COUT编辑一个文件可以是精细的工作,考虑在整个文件中读取(很可能成为字符串的向量)。另一个提示:将程序和操作系统的功能结合起来通常是很方便的。例如,gnu sed有一个--inplace
选项,我已经很好地使用了这个选项,但是使用标准sed
只是在操作程序的帮助下写入stdout并重定向输出并不少见当一个人对结果感到满意时,他可以简单地用新文件覆盖旧文件。例如,sed's/^.//g'some.txt>tmp.txt&&mv tmp.txt file.txt
。原因是操作系统外壳已经很好地处理了文件,并且向stdout写入的功能出人意料地更加广泛。至于手头的主题(这是对先前文章的更正):目前您根本没有回写文件。您可能希望将文件存储在内存中(使用@vu1p3n0x的建议),修改它,然后将其写回磁盘上的文件。我认为重新写入文件的最简单方法是关闭输入流,然后按照建议使用trunc
选项重新打开它进行写入。我先前建议使用seekg
不会截断文件,而只会覆盖开头(您的行数比原来的少)。如果您想要一个可移植的解决方案,那么您应该使用两个文件(或一个临时文件)。如果没有,您可以使用定位并覆盖文件内容。@PeterA.Schneider最简单的方法是最危险的。如果您的程序崩溃,您将丢失文件。安全的方法是保存到其他文件,删除原始文件,然后重命名新文件。但询问者希望使用一个文件:“但我希望输入和输出是同一个文件”我想根本不能保证该行中有一个字符。
std::ifstream filein;
std::string line;
filein.open(help);
std::vector<std::string> temp;
while (std::getline(filein, line))
{
if (!line.empty())
{
if (line[0] == ' ')
{
line.erase(0, 1);
}
}
temp.push_back(line);
}
filein.close();
std::ofstream fileout;
fileout.open(help, std::ofstream::out, std::ofstream::trunc);
int l = 0;
while (l < temp.size())
{
//cout << temp[l] << "\n";
fileout << temp[l] << "\n";
l++;
}
fileout.close();