我的CSV文件构建如下:
1;name;2;5;
2;diff_name;3;5;在阅读下一行之前,我希望能够将5替换为2。所以我正在读这个文件:
file>>number1;
file.ignore( numeric_limits < streamsize >::max(), ';' );
file>>data;诸若此类。我试着这样写:
long pos = plik.tellp();
plik.seekp (pos-2);
plik<<other_number;但它破坏了文件。我不知道是怎么回事,但这并不可靠。pos以某种方式依赖于文件长度,我不能让它每次都这样工作(在文件中使用不同的值)。有没有其他方法来替换这里的值?有什么简单的方法吗?
发布于 2014-09-15 20:50:23
正如Joachim Pileborg在评论中所说的,你不能真的(简单地)直接替换文件中的内容。解决方案是在另一个文件中写入。如果你的第一个文件足够小,你可以使用你的内存来代替第二个文件,并将结果写入第一个文件。
我的代码:
#include <fstream>
#include <iostream>
using namespace std;
int main(){
ifstream ifile("file.csv"); //First file
ofstream ofile("filenew.csv"); //File with replaced fields
char s[100];
string temp;//useful for the replacement
int count=0;//fields counter (useful for replacement)
while(ifile.good()){
ifile.getline(s, 100, ';'); //We read the file field by field
count++;
if(ifile.good()){
if(count==3){ //The third field is stored in a temp variable
temp = s;
}
else if(count==4){//And we put the fourth field before the third
ofile << s;
ofile << ';';
ofile << temp;
ofile << ';';
count=0;
}
else{
if(count==5)count=0;
ofile << s;
ofile << ';';
}
}
}
}https://stackoverflow.com/questions/25846626
复制相似问题