遍历文件,只得到一行

Looping over file, only get one line

假设我们有一个包含以下内容的文本文件:

dogs
cats
bears
trees
fish
rocks
sharks

这些只是用换行符分隔的单词。我正在尝试创建一个 Node.js 插件。插件将通读一个文件并用空行替换匹配的行。假设我向我的程序传递了一个匹配 /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++ 新手,我认为有人可以帮助我在没有 compiling/running 代码的情况下解决这个问题。谢谢。

回答您为什么只读取输入文件的一行的问题:

您第一次写入文件可能会在流上设置 eofbit,因此第二次 getline() 尝试将认为它没有更多可读的内容。

@RSahu 的评论描述了对文本文件执行此操作的最简单方法。