C++中文件的读写操作问题

关于文件的读写

这个是写文件代码

#include
using namespace std;
#include
void test1()
{
    ofstream ofs;
    ofs.open("test.txt", ios::out);
    ofs << "name:sz" << endl;
    ofs << "sex:male" << endl;
    ofs << "age:eighteen" << endl;
    ofs.close();
}
int main()
{
    test1();
    system("pause");
    return 0;
}

这个是读文件代码
```c++
#include
using namespace std;
#include
void test1()
{
    ifstream ifs;
    ifs.open("test.txt", ios::in);
    if (!ifs.is_open())//判断文件是否打开成功
    {
        cout << "文件打开失败" << endl;
        return;
    }
    
    char buf[1024] = { 0 };
    while (ifs >> buf)
    {
        cout << buf << endl;
    }
    ifs.close();
}
int main()
{
    test1();
    
    system("pause");

    return 0;
}

这样为啥显示,文件打开失败?

你得清楚你的文件放在哪个目录下。你这么写的话,文件必须和工程文件在同一个目录下