2010-09-06 67 views
1

我的代碼存在問題。即使在關閉流時也會混合fstream流

它可以寫得很好,如果我殺了閱讀部分。 它可以很好的閱讀,如果我殺了寫部分和文件已被寫入。 2不喜歡對方。這就像寫入流沒有關閉......儘管它應該是。

出了什麼問題?

#include "stdafx.h" 
#include <iostream> 
#include <fstream> 
#include <string> 
using namespace std; 
using namespace System; 

int main(array<System::String ^> ^args) 
{ 
string a[5]; 
a[0]= "this is a sentence."; 
a[1]= "that"; 
a[2]= "here"; 
a[3]= "there"; 
a[4]= "why"; 
a[5]= "who"; 

//Write some stuff to a file 
ofstream outFile("data.txt");  //create out stream 
if (outFile.is_open()){  //ensure stream exists 
    for (int i=0; i< 5; i++){ 
    if(! (outFile << a[i] << endl)){ //write row of stuff 
    cout << "Error durring writting line" << endl; //ensure write was successfull 
    exit(1); 
    } 
    } 
    outFile.close(); 
} 

//Read the stuff back from the file 
if(!outFile.is_open()){ //Only READ if WRITE STREAM was closed. 
    string sTemp; //temporary string buffer 
    int j=0; //count number of lines in txt file 

    ifstream inFile("data.txt"); 
    if (inFile.is_open()){ 
    while (!inFile.eof()){ 
    if(! (getline(inFile, sTemp))){ //read line into garbage variable, and ensure read of line was 
    if(!inFile.eof()){  //successfull accounting for eof fail condition. 
     cout << "Error durring reading line" << endl; 
     exit(1); 
    } 
    } 
    cout << sTemp << endl; //display line on monitor. 
    j++;  
    } 
    inFile.close(); 
    } 
    cout << (j -1) << endl; //Print number lines, minus eof line. 
} 

return 0; 
} 

回答

0

您有內存覆蓋。

你有六根弦,但尺寸只有五串

string a[5]; 
a[0]= "this is a sentence."; 
a[1]= "that"; 
a[2]= "here"; 
a[3]= "there"; 
a[4]= "why"; 
a[5]= "who"; 

這可能會導致你的程序的其他部分有意想不到的行爲。

0

G ...鞠躬恥辱。正在玩文件流,並沒有注意到我衝過來的數組初始化。

有趣的是,MS VS 2005並沒有抱怨陣列值賦值a [5] =「who」。它讓我放棄了它。所以我甚至沒有考慮過在調試過程中。我可以明白爲什麼這樣可以......我在內存中的下一個連續位置寫出了它,並且MS編譯器讓我可以避開它。據我記得Linux確實抱怨這種類型的錯誤。沒有?

認爲這是讀取文件後部分是錯誤的我註釋掉了除ifstream inFile(「data.txt」)行外的所有讀取部分。這會導致應用程序崩潰,導致我認爲寫入流不知何故被關閉。我認爲,當讀取部分的其餘部分被註釋掉時,ifstream inFile(「data.txt」)行中的 僅與該數組無關。然而,這是什麼導致它在VS 2005崩潰。

無論如何,謝謝! 工作正常。