简体   繁体   中英

Writing into a file in C++

I'm trying to write into a file using fstream, but my code is not working. Can you help me what am I doing wrong?

void mem_test()
    {
            fstream filepointer;
            string buffer;

            if ( filepointer.is_open() )
            {
                    filepointer.open("test.t", ios::in | ios::out | ios::binary);
                    getline(filepointer, buffer);
                    getline(filepointer, buffer);

                    filepointer << "TEST!" << endl;
            }
            filepointer.close();
    }

My file test.t (Perimssion to read and write the file in linux):

Example Line 1
Example Line 2
Example Line 3
Example Line 4

Thanks!

You are checking if the file is open before actually opening the file so it should be:

void mem_test()
{
        fstream filepointer;
        string buffer;
        filepointer.open("test.t", ios::in | ios::out | ios::binary);
        if (filepointer.is_open())
        {
                getline(filepointer, buffer);
                getline(filepointer, buffer);
                filepointer << "TEST!" << endl;
                filepointer.close();
        }
}

No need to do the if ( filepointer.is_open() ) check first which will always return false in this case because the file stream has not yet opened a file yet, as a result your code in the if block will not be executed(opening the file which contradicts what you are trying to check in the first place). So open the file first, then check the stream state for error afterward(ie use if(filepointer.is_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