I start to write a code for a shell with some basic functions: open files, save files, create files...
I try to use the ifstream for opening files.
I found the constructor - ifstream openfile("file.txt", ios::in);
I try to use this constructor in the way (function openfile()) that I can enter a filename by cin >> file; and so choos which file to open.
It works when I use it as ifstream openfile("file.txt",ios::in);
Is this constructor a bad choice for that purpose.
Please comment this code, mabe I've done some basic mistakes in the whole logic.

#include <cstdlib>
#include <iostream>
#include <fstream>
using namespace std;
 
/*System variables*/
int runl;
 
/*command variables*/
string command;

/*filemanipulation variables*/
string file="file.txt";

int openfile()
{
    cout << "enter filepath: ";
    cin >> file;
    ifstream openfl(file, ios::in)
    while (openfl.good())
       cout << (char) openfl.get();
       openfl.close();
    cout << endl << "end of the file" << endl;
    return 0;
}

int comminter()
{
    if(command=="exit")
    {
     cout << "interupting SlackeShell..." << endl;
     runl=0;
     return 0;
    }
    if(command=="openfile")
    {
     openfile();
     return 0;
    }                       
    cout << "command not found" << endl;
    return 0;
                            
}

int standby()
{
    cin >> command;
    comminter();
    return 0;    
}

int main()   
{
    cout << endl;
    cout << "SlackeShell 26/06/2006 ver. W002" << endl;
    runl=1;
    while(runl==1)
    {
                  cout << "shell: ";
                  standby();
    }
    return 0;
}

1. it is not necessary to specify ios::in for ifstream, that is what ifstream does anyway.

2. use std::string's c_str() method when passing it to the constructor

ifstream openfl(file.c_str())

3. cin >> file; This construct will work as long as there are no spaces in the filename and optional path. use getline() if it can contain spaces

getline(cin,file)

1. it is not necessary to specify ios::in for ifstream, that is what ifstream does anyway.

2. use std::string's c_str() method when passing it to the constructor

ifstream openfl(file.c_str())

3. cin >> file; This construct will work as long as there are no spaces in the filename and optional path. use getline() if it can contain spaces

getline(cin,file)

I used cin.getline(variable);

int openfile()
{
    char file[10];
    cin.getline (file,10);
    ifstream readfile(file);
    while (! readfile.eof())
          cout << (char) readfile.get();
          readfile.close();
    cout << endl;
    return 0;
}

works fine, Thanks.:lol:

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.