2017-01-02 18 views
3

說我們有這個內容的文本文件:循環執行文件,只得到一個行

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,我認爲有人可以幫助我解決問題,而無需編譯/運行代碼。謝謝。

+2

除非你有很強的理由不這樣做,我會建議使用'的std :: ifstream'打開文件,通過讀取行​​的文件行的內容,變換線節省了'的std ::矢量 ',關閉文件,再次打開文件,但使用'std :: ofstream',寫入'std :: vector '的內容,然後關閉文件。 –

+0

當然,可能是因爲在循環內容時寫入文件總是有點冒險 –

+0

@RSahu但是你有什麼想法,爲什麼我只通過循環一次對於具有多行文本的文件? –

回答

1

要回答你,爲什麼你只讀取輸入文件的一行的問題:

您對文件第一次寫入可能設置在流eofbit,所以第二getline()嘗試會覺得它沒有更多的讀。

來自@RSahu的評論描述了對文本文件執行此操作的最簡單方法。

+0

感謝那個信息,eofbit事情沒有發生在我身上 –