We're a community of 1076K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,075,803 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

ifStream function check if file opens

hello everyone,

I am having a major problem with this assignment that asks to create a function whose input is a reference to an input file, which asks user to enter a file name to open for input, then checks to see where the file opened successfully.
the function returns nothing.

I tried implementing the code so far, however for some reason it doesnt even open a file. The file is saved in the same directory as the program. I have know idea whats going on. Please help!

#include<iostream>
#include<fstream.h>
#include<string>
using namespace std;


int main()

{
    ifstream inFile;
    string inFileName;


    cout << "Enter a filename: ";
    cin >> inFileName;


inFile.open(inFileName.c_str());


system ("pause");
return 1;
}
3
Contributors
2
Replies
19 Minutes
Discussion Span
9 Months Ago
Last Updated
3
Views
mochiboo5
Newbie Poster
7 posts since Aug 2012
Reputation Points: 0
Solved Threads: 0
Skill Endorsements: 0

You can use the is_open() function on the ifstream. As so:

#include<iostream>
#include<fstream.h>
#include<string>
using namespace std;

int main()
{
    ifstream inFile;
    string inFileName;

    cout << "Enter a filename: ";
    cin >> inFileName;

    inFile.open(inFileName.c_str());

    if( ! inFile.is_open() ) {
        cout << "File could not be opened!" << endl;
    } else {
        cout << "File was successfully opened!" << endl;
    };

    system ("pause");
    return 1;
}
mike_2000_17
21st Century Viking
Moderator
3,135 posts since Jul 2010
Reputation Points: 2,050
Solved Threads: 625
Skill Endorsements: 41

Right now you only open the file and do nothing with it. You need to check if the file even exists first. Try adding this on line 19

if (!inFile)
    {
        cout << "ERROR 404: FILE NOT FOUND!!";
    }

And then you have to close the file once you're done reading it.

inFile.close();

If you want to learn more see here

http://www.cplusplus.com/doc/tutorial/files/

Karkalash
Newbie Poster
22 posts since Apr 2008
Reputation Points: 17
Solved Threads: 0
Skill Endorsements: 0

This article has been dead for over three months: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page rendered in 0.0660 seconds using 2.72MB