简体   繁体   中英

Writing file doesn't work properly

I'm trying to save some of my input to a file, but it doesn't seem to work. I don't know if its the file extension or whatever, but I've tried to modify it for an hour now, however it doesn't pop-up some file in my folder.

This is how my code works (not posting everything, would be too long)

This is my function:

void mobiltelefon::savePhoneOnFile() const
{
    ofstream out;
    out.open("C:\\temp\\phones.txt", ios::in);
    out << this->numberofphones << endl;
    for (int i = 0; i < this->numberofphones; i++) {
        out << this->phones[i]->getPhonename() << endl;
        out << this->phones[i]->getPrice() << endl;
    }
    out.close();
}

This is how I call it in main :

case 7:
    cout << "Save the phones on file" << endl;
    fb.savePhoneOnFile();
    break;

I can't see my mistake. Why doesn't the file show up a file in my folder when I try to save it?

If you are trying to open the file for writing, you should be using ios::out as the second argument

ofstream out("C:\\temp\\phones.txt", ios::out);

The various open modes are

app seek to the end of stream before each write
binary open in binary mode
in open for reading
out open for writing
trunc discard the contents of the stream when opening
ate seek to the end of stream immediately after open

Here:

ofstream out;
out.open("C:\\temp\\phones.txt", ios::in);

You don't want to have the std::ios::in flag. Why would you? You're writing to a file, not reading from it.

Explained: std::ofstream bitwise-ORs the flag argument with std::ios_base::out in its constructor and passes it to std::basic_filebuf::open . Look up out | in out | in in that link and you have the answer. The file would need to exist to be open properly. It won't be created.

Just leave out that parameter completely and it will be defaulted to std::ios_base::out (that's what you should have had):

out.open("C:\\temp\\phones.txt");

You might as well do it at once at construction:

std::ofstream out("C:\\temp\\phones.txt");

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