说我们有这个内容的文本文件:循环执行文件,只得到一个行
dogs
cats
bears
trees
fish
rocks
sharks
这些都只是换行字符分隔单词。我正在尝试创建一个Node.js插件。 Addon将读取文件并用空行替换匹配的行。假设我将我的程序传递给匹配/trees/
的正则表达式。如果我的文件传递给我的C++程序会读取+写入文件,并导致:眼下
dogs
cats
bears
fish
rocks
sharks
,问题是它不是通过文件中的所有行循环。我觉得这是在追加模式下打开文件,因此只是从文件的末尾开始?我不知道。 无论如何,我想编辑文件,而不是截断并重写或替换整个文件,因为这会中断正在拖动文件的进程。
下面的代码:
#include <nan.h>
#include <fstream>
#include <sstream>
#include <string>
#include <iostream>
using namespace std;
void Method(const Nan::FunctionCallbackInfo<v8::Value>& info) {
info.GetReturnValue().Set(Nan::New("world").ToLocalChecked());
}
void Init(v8::Local<v8::Object> exports) {
fstream infile("/home/oleg/dogs.txt");
if(infile.fail()){
cerr << " infile fail" << endl;
exit(1);
}
int pos = 0;
string line;
int count = 0;
while (getline(infile, line)){
// we only seem to loop once, even though the file has 7 or 8 items
count++;
long position = infile.tellp();
cout << "tellp position is " << position << endl;
string str(line);
int len = str.length();
cout << " => line contains => " << line << endl;
cout << " line length is " << len << endl;
std::string s(len, ' '); // create blank string of certain length
infile << s; // write the string to the current position
pos = pos + len;
cout << "pos is " << pos << endl;
}
cout << " => count => " << count << endl;
infile.close();
exports->Set(Nan::New("hello").ToLocalChecked(),
Nan::New<v8::FunctionTemplate>(Method)->GetFunction());
}
NODE_MODULE(hello, Init)
编译代码,您可能需要使用Node.js的工具,如果你想帮助,并希望尝试编译这是
node-gyp rebuild
代码,然后让我知道,因为你可能需要更多的信息。但我是一个新的C++ newb,我认为有人可以帮助我解决问题,而无需编译/运行代码。谢谢。
除非你有很强的理由不这样做,我会建议使用'的std :: ifstream'打开文件,通过读取行的文件行的内容,变换线节省了'的std ::矢量 ',关闭文件,再次打开文件,但使用'std :: ofstream',写入'std :: vector '的内容,然后关闭文件。 –
当然,可能是因为在循环内容时写入文件总是有点冒险 –
@RSahu但是你有什么想法,为什么我只通过循环一次对于具有多行文本的文件? –