读取 .txt 文件的第二行并写入另一个 .txt 文件 - C++
reading .txt file's 2nd line and write to another .txt file - C++
我有 79 个 .txt
个这样的文件:
iRun iDate showerEnergy thetaRad phiRad totalShowers totalParticles e+ e- μ+ μ-
4001 121125 5e+07 1.61401 0.00118607 1 9929166 6909475 1271116 1399686 151330 148624
-1 4001 121125 5e+07 1.61401 0.00118607 2 9929167 6909475 1271116 1399686 151330 148624
它只有 3 行,第一行是 iRun iDate
,第二行是 4001
,第三行是 -1
。我只想阅读这些文本文件的第二行。如果我清楚地阅读它们,我还想将所有 79 个文本文件的第二行写在一个文本文件中。
这对于 <fstream>
来说非常简单。一个非常基本的程序看起来像这样:
#include <fstream>
#include <string>
int main() {
std::ifstream infile("indata.txt"); // Open input file
std::string lineData = "";
getline(infile, lineData); // Get first line.
getline(infile, lineData); // Get second line.
std::ofstream outfile;
outfile.open("outdata.txt", std::ios_base::app);
outfile << lineData << std::endl; // Append lineData to outfile. Creates the file if necessary.
return 0;
}
试着写点东西。
伪代码如下所示
open outfile
for each text file
{
open file
skip line
read line
write line to out file
close file
}
close output file
所以您要做的第一件事就是弄清楚如何枚举文件。两个选择:
- 通过参数在命令行中传递它们。在 unix 上,shell 将扩展,例如,in*.txt 到实际文件名列表
- 使用一些函数来获取文件列表。 c 方式 How do you get a directory listing in C? or the c++ way How do I get a list of files in a directory in C++?
剩下的就是简单的c++文件io
如果这是一个实际问题(与 class 作业相反)我会使用 awk、perl、sed 等而不是编写代码
我有 79 个 .txt
个这样的文件:
iRun iDate showerEnergy thetaRad phiRad totalShowers totalParticles e+ e- μ+ μ-
4001 121125 5e+07 1.61401 0.00118607 1 9929166 6909475 1271116 1399686 151330 148624
-1 4001 121125 5e+07 1.61401 0.00118607 2 9929167 6909475 1271116 1399686 151330 148624
它只有 3 行,第一行是 iRun iDate
,第二行是 4001
,第三行是 -1
。我只想阅读这些文本文件的第二行。如果我清楚地阅读它们,我还想将所有 79 个文本文件的第二行写在一个文本文件中。
这对于 <fstream>
来说非常简单。一个非常基本的程序看起来像这样:
#include <fstream>
#include <string>
int main() {
std::ifstream infile("indata.txt"); // Open input file
std::string lineData = "";
getline(infile, lineData); // Get first line.
getline(infile, lineData); // Get second line.
std::ofstream outfile;
outfile.open("outdata.txt", std::ios_base::app);
outfile << lineData << std::endl; // Append lineData to outfile. Creates the file if necessary.
return 0;
}
试着写点东西。
伪代码如下所示
open outfile
for each text file
{
open file
skip line
read line
write line to out file
close file
}
close output file
所以您要做的第一件事就是弄清楚如何枚举文件。两个选择:
- 通过参数在命令行中传递它们。在 unix 上,shell 将扩展,例如,in*.txt 到实际文件名列表
- 使用一些函数来获取文件列表。 c 方式 How do you get a directory listing in C? or the c++ way How do I get a list of files in a directory in C++?
剩下的就是简单的c++文件io
如果这是一个实际问题(与 class 作业相反)我会使用 awk、perl、sed 等而不是编写代码