2016-09-14 4 views
-1

1.i行ごとにファイルを読み込もうとしていますが、それはできません。私は以前、問題なく1つのステップでファイル全体を読み込んでいました。私は、データを受け取るベクトルを実験としてローカルベクトルに変更しました(成功なし)。私は、私にとっては明らかに間違ったことをしていると思う。fstreamを使用して行単位でファイルを読み取ることはできません。ファイル全体で読み取るok

int 
full_file_read(std::vector<std::string> &data , 
       const std::string& filename , 
       bool is_binary) 
{ 
    std::string line ; 
    std::ios_base::openmode openmode = std::ios::ate | std::ios::in ; 

    if (is_binary) 
    { 
     openmode |= std::ios::binary ; 
    } 

    std::fstream file(filename , openmode) ; 

    if (!file) 
    { 
     std::cerr << "Can't open input file! " 
      << filename << std::endl ; 
    } 

    std::vector<std::string> text ; 
    // to verify that it likes the push back for data is not the problem 

    if (file.is_open()) 
    { 
     while (std::getline(file , line)) 
     { 
      text.push_back(line) ; 
      // data.push_back(line) ; 
     } 
    } 
    else 
    { 
     std::cerr << "Opening of " << filename 
      << " failed!" << std::endl ; 
    } 

    std::cout << "file contents: " << std::endl ; 

    for (auto const& c : line) 
    { 
     std::cout << c << ' ' << std::endl ; 
    } 

    return 0 ; 
} 

2.デバッグを使用しないで実行すると、seg-faultが発生します。 gdbのwhileループは実行されません。

i have a comment here 
and another over there 
yet another in somewhere unknown 
for reasons only (dr) who noses 
NumParticles|SimWidth|SimHeight|ViewWidth|ViewHeight|Softener|Zoom|MouseX|MouseY|MassMin|MassMax|CenterMass|DiskMin|DiskMax 
10000000,327680,327680,1366,768,10,1,0,0,1,2,100000,2000000,5 

TIA

+0

私はその変更を行い、エラーを指摘してくれてありがとう。今は奇妙な部分のために:ファイルを読み込んで、行をエコーし​​てreturn文に行きますが、そうではありません。開いた文に戻ります。奇妙な!! – awb

答えて

1

std::ios::ateは、ファイルの最後で開くことを意味し、次のようにデータファイルがあります。一般的には、ファイルに書き込む場合にのみこれを使用し、読み込み中は使用したくありません。これを含めることで、最初にgetlineにファイルの終わりが得られます。

私はsegfaultについて説明できません。これは、一般に未定義の動作が原因です。おそらく、この関数が復帰した後のコードにあります。

+0

私はその変更を行い、エラーを指摘してくれてありがとう。今は奇妙な部分のために:ファイルを読み込んで、行をエコーし​​てreturn文に行きますが、そうではありません。開いた文に戻ります。奇妙な!! (私はちょうどこれに慣れているように還元人の発言を赦してください) – awb

+0

心配しないで!今問題は呼び出し関数にあるので、これを解決する/閉じる – awb

関連する問題