我的代碼存在問題。即使在關閉流時也會混合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;
}