[英]C++ copying parts of a file to a new file
我正在尝试使用来自两个不同现有文件的数据创建一个新文件。 我需要完整地复制第一个现有文件,这已成功完成。 对于第二个现有文件,我只需要复制最后两列,并将其附加到每行末尾的第一个文件中。
例如:
来自第一个文件的信息已复制到我的新文件中:
20424297 1092 CSCI 13500 B 3
20424297 1092 CSCI 13600 A- 3.7
现在,我需要复制此文件中每行的最后两列,然后将它们附加到上面文件中的相应行:
17250 3.00 RNL
17381 3.00 RLA
即我需要在第一行的末尾附加“ 3.00”和“ RNL”,在第二行的末尾附加“ 3.0”和“ RLA”,依此类推。
这是我到目前为止的内容:
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <cstdlib>
using namespace std;
int main() {
//Creates new file and StudentData.tsv
ofstream myFile;
ifstream studentData;
ifstream hunterCourseData;
//StudentData.tsv is opened and checked to make sure it didn't fail
studentData.open("StudentData.tsv");
if(studentData.fail()){
cout << "Student data file failed to open" << endl;
exit(1);
}
//My new file is opened and checked to make sure it didn't fail
myFile.open("file.txt");
if(myFile.fail()){
cout << "MyFile file failed to open" << endl;
exit(1);
}
//HunterCourse file is opened and checked to make sure if didn't fail
hunterCourseData.open("HunterCourse.tsv");
if(myFile.fail()){
cout << "Hunter data file failed to open" << endl;
exit(1);
}
// Copies data from StudentData.tsv to myFile
char next = '\0';
int n = 1;
while(! studentData.eof()){
myFile << next;
if(next == '\n'){
n++;
myFile << n << ' ';
}
studentData.get(next);
}
return 0;
}
我要去弄香蕉想办法解决这个问题。 我敢肯定这是一个简单的修复程序,但是我找不到任何有效的在线方法。 我已经研究过使用ostream和while循环将每一行分配给一个变量,但是我无法使其正常工作。
我已经想到的另一种方法是从第二个文件中删除所有整数,因为我只需要最后两列,并且这些列都不包含整数。
如果您看一下文件流的seekg方法,您会注意到第二个版本允许您实现设置偏移位置的位置(例如ios_base::end
,该位置将偏移量设置为与使用此文件,您可以有效地从文件末尾向后读取。
int Pos=0;
while(hunterCourseData.peek()!= '\n')
{
Pos--;
hunterCourseData.seekg(Pos, ios_base::end);
}
//this line will execute when you have found the first newline-character from the end of the file.
这个非常相似的问题提供了更好的代码
另一种可能性就是简单地事先查找文件中有多少行。 (速度较慢,但可行),在这种情况下,只需循环调用getline
的文件并递增count变量,将其重置为开始,然后重复直到达到count - 2
。 虽然我自己不会使用这种技术。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.