Jefree Sujit
Jefree Sujit

Reputation: 1586

How to open a file that the user gives in output screen using c++

I want the user to give the file name in output screen,for the file to be opened while running the program .More specifically, if the user gives a file name in output screen, my program should open that file for him. How can i code this using files in c++? Can anyone give an example?

Upvotes: 0

Views: 1747

Answers (1)

stellarossa
stellarossa

Reputation: 1800

example code:

#include <iostream>
#include <fstream>

int main() {
    std::string filename, line;
    std::cout << "Input file name: ";
    std::cin >> filename;

    std::ifstream infile(filename);
    if(!infile)
        std::cerr << "No such file!" << std::endl;
    else {
        std::cout << "File contents: " << std::endl;
        while(infile >> line)
            std::cout << line << std::endl;
    }
}

contents of test.txt:

hello
world
how
are
you

program output (on console):

Input file name: test.txt
File contents: 
hello
world
how
are
you

the way this works is, you declare two strings - one that will be the filename and the other that will be serve as a temporary buffer for each line in file. when the user inputs a file name, depending on whether the file exists or not, the program will either output an error, or declare and initialize a file stream infile (this basically opens a stream to your file and allows you to extract [or input] data from the desired file).

once that is done, the program will read the file line by line while(infile >> line) and output the contents of each file to console.

Upvotes: 1

Related Questions