How to prevent file.open() from displaying file's contents

I am a beginner to C++, so please keep it simple. I am currently learning how to work with files, and when using file.open() [Supposing file is a variable that contains the file's name], how do I prevent it from displaying all the file's contents to the console?

I am currently learning how to work with files, and when using file.open() [Supposing file is a variable that contains the file's name],

If you do this
 
    string file = "example.txt";
then
 
    file.open();
would generate a syntax error. (A string cannot be opened).

You could do something like this:
1
2
    string filename = "example.txt";  // define variable containing name of file.
    ifstream infile(filename); // define and open file 


how do I prevent it from displaying all the file's contents to the console?

You don't need to do anything at all.

If you want to display the contents of the file on the console, then you do need to write code to do that.

For example you might do this:
1
2
3
4
5
6
7
8
    ifstream infile("example.txt"); // define and open file

    // Additional code to read and display contents of file 
    string line;
    while (getline(infile, line))
    {
        cout << line << '\n';
    }


Notice it takes extra code to display the contents of the file. If you don't want to do that, then don't write that extra code.

See the tutorial for more examples and explanations:

http://www.cplusplus.com/doc/tutorial/files/
Last edited on
How would I hide the file's contents from the standard output?
Last edited on
By the above I mean how do I stop my file's contents from displaying?
As I said, you don't need to stop it. You need to not do it.

If we take this example:
1
2
3
4
5
6
7
8
    ifstream infile("example.txt"); // define and open file

    // Additional code to read and display contents of file 
    string line;
    while (getline(infile, line))
    {
        cout << line << '\n';
    }


To achieve your desired behaviour, change the code to this:
 
    ifstream infile("example.txt"); // define and open file 
What he is saying is that the act of opening a file does not display it. You must have an example that is displaying it, but the open statement does NOT.
Topic archived. No new replies allowed.