Computing.Net > Forums > Programming > c++ file I/O, open/close file

Computing.Net: Over 1,000,000 posts about all things technology related! Over 90% answered within 24 hours! Click here to sign up now, it's free!

c++ file I/O, open/close file

Reply to Message Icon

Original Message
Name: Clicker
Date: September 20, 2004 at 11:32:19 Pacific
Subject: c++ file I/O, open/close file
OS: win xp
CPU/Ram: 1.6 Gig / 512 Meg
Comment:

Hi all,

before i begin, yes this is an homework assignment question...

got a c++ file I/O question. here is the code that i've so far.

#include <iostream>
#include <sting>
#include <fstream>

int main()
{
string inputFileName;

ifstream inputFile;

cout << "enter file name";
cin >> inputFileName;

inputFile.open (inputFileName.c_str());

// if file fails to open/exist
while(inpuFile == NULL)
{
cout << "enter file name";
cin >> inputFileName;
inputFile.open (inputFileName.c_str());
}
// if the file open successfully, exit loop

return 0;
}

so the purpose is if the input file name entered by the user does not exist or fail to open then keep looping throuh until the file opens.

to test it out, i give the wrong file name so the loop is executed, then i provide the correct file name...it does not open the file and i keep looping through..

i'm probably doing something wrong with ( inputFile == NULL ) condition...please help

thanks in advance

Clicker


Report Offensive Message For Removal


Response Number 1
Name: Infinite Recursion
Date: September 20, 2004 at 12:30:43 Pacific
Reply: (edit)

You have some of your variables mis-spelled. Need to correct that first... first instance: In your while loop you have
'inpuFile' and not 'inputFile'.

---

inFile.open(filename_in.c_str());

Try the following:

fstream has a fail()

cout << "inFile.fail() = "<< inFile.fail() << endl; // fail() = 1 if file exists

OR

if(!inFile)
{...}


IR


Report Offensive Follow Up For Removal

Response Number 2
Name: egkenny
Date: September 20, 2004 at 17:10:56 Pacific
Reply: (edit)

Close but you need to clear the fail bit. After the fail bit is set even a success will not clear it.

while(inputFile.fail())
{
inputFile.clear();
cout << "enter file name";
cin >> inputFileName;
inputFile.open (inputFileName.c_str());
}


Report Offensive Follow Up For Removal

Response Number 3
Name: Tugg
Date: September 24, 2004 at 04:24:53 Pacific
Reply: (edit)

Looks like a typo but your second include call in the program calls sting...you probably meant string

#include <string>

~Tugg~


Report Offensive Follow Up For Removal







Post Locked

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.


Go to Programming Forum Home








Do you own an iPhone?

Yes
No, but soon
No


View Results

Poll Finishes In 7 Days.
Discuss in The Lounge
Poll History




Data Recovery Software