In: Computer Science
Need to check if File is successfully opened? C++
It works when I input the right txt file. But, it keeps stating, File successfully open." even I put in a non-existing file.
Here are the specifications:
Develop a functional flowchart and then write a C++ program to solve the following problem.
Create a text file named first.txt and write your first name in the file. You will be reading the name of the file from the keyboard as a string, using the string class. Your program will also read your first name from the keyboard. The process of the file creation (name of the file, mode for opening the file, and testing the open success is done in a user-defined function. The function communicates the status of file open to the calling function).
Here is what I have:
#include<string>
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
int main() {
string file; //This is a declaration for a file name
string firstname;
ofstream myfile;
cout << "Please enter the file name of your
first name:";
cin >> file;
myfile.open(file);
if (myfile.is_open())
{
cout << "\nFile successfully
open.\n";
}
else
{
cout << "Error opening
file";
}
cout << "Please enter your first name:";
//asks the user to input first name
cin >> firstname; //user inputs first name
myfile << firstname;
myfile.close(); //closes the file
#include<string>
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
bool fileOpen(string fileName, ofstream &out, bool
mode){
out.open(fileName, mode);
if(out.is_open()){
return true;
}
else{
return false;
}
}
int main() {
string file; //This is a declaration for a file
name
string firstname;
ofstream myfile;
cout << "Please enter the file name of your
first name:";
cin >> file;
if (fileOpen(file, myfile, ios::out))
{
cout << endl << "File
successfully opened." << endl;
cout << "Please enter your
first name:"; //asks the user to input first name
cin >> firstname; //user
inputs first name
myfile << firstname;
myfile.close(); //closes the
file
}
else
{
cout << "Error opening file"
<< endl;
}
}