mixing fstream streams issue even when closed streams
I am having problems with the code bellow.
It can write fine if i kill the read section. It can read fine if i kill the write section and the file has already been written. The 2 don't like each other. It is like the write stream is not closed... though it should be.
What is wrong?
#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.
}开发者_StackOverflow中文版
return 0;
}
You have a memory overwrite.
You have six strings, but dimension only for five strings
string a[5];
a[0]= "this is a sentence.";
a[1]= "that";
a[2]= "here";
a[3]= "there";
a[4]= "why";
a[5]= "who";
this can cause the rest of your program have unexpected behavior.
G... bows head in shame. Was playing with file streams and wasn't paying attention to the array initializations that i rushed through.
What is interesting is that MS VS 2005 did not complain about the array value assignment a[5]= "who". It let me get away with it. So I didn't even consider that durring debugging. I can kind of see why that is ok... I wrote it out of bounds in the next contiguous spot in memory and the MS compiler let me get away with it. As far as I remember Linux does complain about this type of error. No?
Thinking it was the read file back section that was wrong i commented out all of the read section except the line ifstream inFile("data.txt"). This cause the app to crash, leading me to think the write stream was somehow not closed. I take it that the ifstream inFile("data.txt") line alone has little to do with the array in question when the rest of the read section is commented out. Yet that is what caused it to crash in VS 2005.
At any rate, thanks! Works fine.
精彩评论