Click to See Complete Forum and Search --> : fstream and variable filenames


penth
November 3rd, 2005, 11:44 AM
I've got a program that formats a data file and outputs it to a different filename.



My input looks like this

ifstream openFile ("BATCH002.DAT");
if (openFile.is_open())
{

while (! openFile.eof() )
{

getline (openFile,line);

oneArray[q] = stripSpace(line);

q++;

}

openFile.close();

my output looks like this:

ofstream outputFile("OUTPUT2.TXT");
if (outputFile.is_open())
{
for (int k = 0; k < arrayHeight; k++)
{
if (oneArray[k] != "") outputFile << oneArray[k] << "\t\t\t\t" << twoInts[k] <<"\n";
}

outputFile.close;
}
else cout << "Error opening file.";
}

I don't want the input and output filenames hard coded. I know you can use argv and argc in the main() to get the command line arguments into variables. The problem is that when I replace "BATCH002.DAT" or "OUTPUT2.TXT" with a variable my program errors.

Marc G
November 3rd, 2005, 11:51 AM
How does your program "errors"?
Compile time errors?
Runtime errors?
Post the exact error.

7stud
November 3rd, 2005, 01:30 PM
1)All functions expect particular arguments and the ifstream() constructor is no exception. The type you feed it must be the type it is expecting. Post your actual code, the errors, and put a comment on the line in your program indicating where the error is occuring.

2)Use code tags around your code(click on the "vB code" link in the bottom left hand corner of the page to see how) .

3) In order for the reading from the file to end correctly, your read statement should be the while loop conditional:

while( getline(...) )

getline() returns an object that will evaluate to false if an error occurs while reading from the file. End of file is considered an error. However, there are other errors that can occur as well, and the way you have it now, if one of those errors occurs, then you'll enter an infinite loop. That will happen because eof won't be reached, but every attempt to read from the file will fail because of the error, so your loop will go 'round and 'round, never hitting eof. You need to end your loop on any error--not just eof.