首页 > 解决方案 > 当我们在不打开文件的情况下写入文件时,内部会发生什么?

问题描述

例如,如果我写入一个文件,该文件不在我的 << 给定要写入的字符串所在的位置?

int main(int argc, char** argv) {
    fstream my_file;

    if (argc>1)
    {
            my_file.open("my_file.txt", ios::out);
            cout << "File1 created successfully!"<<endl;
    }


    my_file << "Guru99";
    my_file.close();
    cout<<"Done"<<endl;

    return 0; }

它会把它放在内存中还是放在 dev/null 类型的区域中?

标签: c++filefile-handlingiostream

解决方案


如果您尝试写入fstream与文件无关(未打开)的对象,您的输出将被丢弃并failbit设置:

如果无法生成输出,则设置失败位,如果在此流的异常掩码中启用了失败位上的异常,则抛出 ios_base::failure。

https://en.cppreference.com/w/cpp/named_req/FormattedOutputFunction中所述。


推荐阅读