简体   繁体   中英

C++ open() not working for any apparent reason

ifstream infile;
infile.open("BONUS.txt");

string info;

    if (!infile)
        cout << "File Open Failure" << endl;
    else
    {
        while (infile >> info)
            cout << info << endl;
            infile.close();
    }

This is my code. And no matter what I do, my file always fails to open. It enters the if and exits. What could possibly be the problem? My text file is saved in the correct directory and nothing seems to be wrong with it.

There are two parameters in open() , file to be opened and mode. The mode refers to what you can do with that file, ie write to, read from, etc.

There are six possible modes when using open() :

  1. Parameter in stands for input. The internal stream buffer enables input. (Use for reading the file.)
  2. Parameter out stands for output. The same internal buffer enables output. (Use for writing to the file.)
  3. Parameter binary allows all operations to be done in binary, instead of text.
  4. Parameter ate stands for at end and begins output at the end of the file.
  5. Parameter app stands for append and output events happen at the end of the file.
  6. Parameter trunc stands for truncate . All contents in existence before it is opened are deleted.

It seems that you want to write to the file, in which case use out .

ifstream infile;
infile.open("BONUS.txt", out);

If you are not using the correct mode, the function will fail. If you have any more questions, Google fstream::open() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM