2010-09-06 70 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崩溃。

无论如何,谢谢! 工作正常。