C++的文件输入输出流如何设置输出路径

比如说我要输出一个字符串"Hello World!"到文档a.txt中,我需要这个文档生成在c:\helloworld
注意是文件输入输出流
谢谢。

#include<iostream>
#include<fstream>
using namespace std;
void main()
{
ofstream ofile;
ofile.open("c:\\helloworld.txt");
cout << "Hello World!" << endl;
ofile << "Hello World!" << endl;
ofile.close();
}

在这行代码  ofile.open("c:\\helloworld.txt");

将路径输入双引号内即可。

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2016-09-26

用<fstream>的ofstream类来创建文件输出流。可以在构造函数里直接指定文件路径,也可以使用open函数打开。

http://www.cplusplus.com/reference/fstream/ofstream/

参考代码

#include<fstream>

int main()
{
    std::ofstream fout("C:\helloworld\a.txt");
    fout << "Hello World!";
    fout.close();
    return 0;
}

本回答被提问者和网友采纳
第2个回答  2018-06-27
    const char *fileName = "C:\\helloworld\\test.txt";

    ofstream ofs(fileName);
    if(!ofs) {
        cout << "Cannot open file.\n";
        return 1;
    }

    ofs << 10 << " " << 123.23 << "\n";
    ofs << "This is a text.";

    ofs.close();

相似回答