-
ifstream problem
Im trying to do this in dev c++
Im basically open a large list which contains filenames to parse
and store the results.
Now what im trying to do here is to open an close a file in order to be able to "parse" a number of files (which are saved in a list)
Code:
ifstream l_file("list.txt"); //text containing list of files.
ifstream a_file; //the file to be parsed
ofstream b_file("final.txt"); //file which will be filled with the result
while (!l_file.eof()) //open the file list
{
l_file>>fname; //send the file to the filename
a_file.open(fname); //open the text containing emails
cout<<"filename:"<<fname<<":"<<a_file.is_open()<<endl;
while (!a_file.eof())
{
a_file>>str;
if (parseline(str)!='\0')
{
cout<<"linea:"<<str<<endl;
cout<<"lineap :"<<parseline(str)<<endl;
b_file<<parseline(str)<<endl; //save the parsed data
}
}
a_file.close();
a_file.clear();
}
l_file.close ();
b_file.close ();
getch();
return 0;
}
I know Is not an ellegant solution (Suggestions accepted :)) but is the first one I thought of
It looks like it should work right? well when I try to open the a_file for a second time, the program crashes. thats why I added a_file.clear but it doesnt work. is there a way to use an ifstream with 2 diferent files without crashing? how do you actually close a filestream?
p.s.
oh yeah, the list contains the same file like this
example.txt
example.txt
so is not a file missing problem.
-
Try to use getline instead of >> when getting the filenames. Also, always check wether your File.open() succeeds or fails. I guess that this is why your program crashes (no need for clear, you can reopen a file assuming you close it first, which you did).
The code below works just fine.
Code:
#include <fstream.h>
int main()
{
//Data
char Buffer;
char FileName[256];
ifstream FileList;
ifstream File;
ofstream NewFile;
//Attempt to open the list of filenames
FileList.open("FileList.txt", ios::in);
if(FileList.fail())
{
return 0;
}
//Attempt to open the output file
NewFile.open("Result.txt", ios::out);
if(NewFile.fail())
{
FileList.close();
return 0;
}
//Loops though all filenames in the list
while(!FileList.eof())
{
//Open the files in the list one by one
FileList.getline(FileName, 255);
File.open(FileName, ios::in);
if(!File.fail())
{
while(!File.eof())
{
//Read one byte
File.get(Buffer);
//Filter out EOF character
//(There must be a better way than this...)
if(Buffer != 'ÿ')
{
NewFile << Buffer;
}
}
//Add a newline (formating purposes)
NewFile << endl;
File.close();
}
}
//Exit
FileList.close();
NewFile.close();
return 0;
}
If someone knows a better way to remove the EOF character at the end of the file, plz tell :).
-
Thank you.
Well that didnt solved the problem but you did gave me a head start on where to look, aparently the best way to do this is to use dynamic memory allocation to close and recreate this kind of streams in dev c++ it might not be entirely correct since I havent used it much, but it worked for me.
:)
Thanks for the tips anyway.