fstream loading text file into char array

Started by
2 comments, last by SiCrane 13 years ago
Hello I am trying to get a text file to load up through this bit of code here and get put into a char array but it wont let me, It says my array is corrupt ... any ideas?

int MenuRead(string SaveFileNameInfo)
{
char FILE[255];
char acTemp;
ifstream in(SaveFileNameInfo, ios::in | ios::binary);
if(!in)
{
cout << "can't open file! " << SaveFileNameInfo << endl;
return 1;
}

while(in)
{
in.get(acTemp);
if(in) cout << acTemp;
FILE[255] = acTemp;
}
in.close();
cout << FILE;
return 0;}
Advertisement
Firstly, char FILE[255] has 255 entries, starting at 0, so the last valid entry is 254, not 255 that you write in your loop. This could potentially crash your program.
Secondly, why do you write to FILE[255] always?
That will just keep overwriting the same (in this case invalid) entry over and over again, replacing the previous value. I guess you want to start writing at FILE[0] and then FILE[1] etc.
Thirdly, you should add a check to abort if you get too many characters, or your program will crash if the file is too big.
And lastly, it's better to remove the array entirely, and read into strings, one line or word at a time, depending on what kind of file you are dealing with and what you want to use the contents for.
i just cant get the text file to go into a char array
Did you have troubles understanding the previous post? If so, what exactly did you not understand? If you did understand the previous post, how have you adjusted your code?

This topic is closed to new replies.

Advertisement