在 C++ 中,从文件找到一行后从该位置复制到该文件的末尾
copying after a line has been found from a file from that position till the end of that file in c++
我有一个文件,其中包含蛋白质坐标以及它前面的其他信息。我的目标是查找名为"$PARAMETERS"的某一行,然后从那里复制它之后的每一行,直到文件末尾。
我怎样才能完成呢?这是我编写的整个程序的一部分小代码(这是其他人几年前编写的,我接手升级了他的代码以进行研究):
ifstream InFile;
InFile.open (DC_InFile.c_str(), ios::in);
while ( not InFile.eof() )
{
Line = NextLine (&InFile);
if (Line.find ("#") == 0) continue; // skip lines starting with # (comments)
if (Line.length() == 0) continue; // skip empty lines
size_t pos = Line.find("$PARAMETERS");
Line.copy(Line.begin("$PARAMETERS")+pos, Line.end("$END"));
&Line.copy >> x_1 >> y_2 >> z_3;
}
请记住,我将行定义为string
我想你需要在$PARAMETERS
和$END
之间读取数据,而不是从$PARAMETERS
到文件末尾。如果是这样,您可以使用以下代码:
string str;
while (getline(InFile, str))
{
if (str.find("#") == 0)
continue;
if (str.length() == 0)
continue;
if (str.find("$PARAMETERS") == 0)
{
double x_1, y_2, z_3; // you want to read numbers, i guess
while (getline(InFile, str))
{
if (str.find("$END") == 0)
break;
stringstream stream(str);
if (stream >> x_1 >> y_2 >> z_3)
{
// Do whatever you want with x_1, y_2 and z_3
}
}
}
}
这将处理多个数据部分;不确定您是否真的需要此行为。
例如:
# comment
$PARAMETERS
1 2 3
4 5 6
$END
#unrelated data
100 200 300
$PARAMETERS
7 8 9
10 11 12
$END
我不确定你想要复制文件的第一行是什么,但假设你明白了,并且你没有阅读超过当前行的内容,你可以像这样复制你正在阅读的 fike 的尾巴:
out << InFile.rdbuf();
此处out
是您要将数据发送到的std::ostream
。
请注意,您不应该使用InFile.eof()
来确定是否有更多数据!相反,您应该读取要读取的内容,然后检查读取是否成功。您需要在阅读后进行检查,因为流在您这样做之前无法知道您尝试阅读的内容。
跟进迪特马尔的回答:在我看来,这听起来像你应该使用std::getline
,直到找到一行匹配您的模式。 如果您希望该行作为您的输出,然后输出它,然后使用 Dietmar 的解决方案复制文件的其余部分。 像这样:
while ( std::getline( in, line ) && ! isStartLine( line ) ) {
}
if ( in ) { // Since you might not have found the line
out << line << 'n'; // If you want the matching line
// You can also edit it here.
out << in.rdbuf();
}
并且不要放各种复杂的解析信息,与continue
和break
,在循环中。 结果是两者不可读且不可维护。 将其分解为一个简单的功能,如上所述:您还将有更好的机会获得没错。 (就您而言,您应该匹配"$PARAMETERS #
xxx"
,还是不匹配? 在单独的函数中,更容易获得没错。
相关文章:
- 更改.cpp程序的输入文件中数据的位置会意外更改输出
- 如何选择在 csv 文件中输出的位置
- 无法打开 fstream C++文件,即使它与 .cpp 位于同一位置
- 如何在特定位置追加 json 文件
- 将文件复制到自定义位置,存在字符串转换问题
- 奇怪的Arduino C++编译错误取决于文件位置
- 在 elf 文件中查找全局变量的位置
- 可以将Boost消息队列文件重定向到用户指定的位置
- 您如何确定 MySQLCPPConn 库文件的位置?
- 是否可以将要"ShellExecute"的文件包含在 dll 中?如果是这样,"ShellExecute"中的文件位置应该是什么?
- 快速访问 ifs() C++中的文件位置
- 从C++中父文件夹的父文件夹提供文件位置
- MFC 打开文件位置并选择(突出显示)该文件
- 如何从HTTP在C++中打开一个URL不是文件位置的文件
- 如何处理不同 Linux 发行版上的不同头文件位置
- 配置文件位置和二进制文件,并构建像autoconf这样的系统
- 文件类型以编程关联和文件位置(Windows)
- Visual Studios (2012 pro 主要是) <从父级继承或项目默认值的默认值的文件位置>
- Tesseract -更改语言文件位置
- 更改Xcode c++应用程序外部文件位置