在C ++中的特定路径中写入文件 [英] Write a file in a specific path in C++

查看:578
本文介绍了在C ++中的特定路径中写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码成功写入一个文件:

  ofstream outfile 
outfile.write(buffer,size);
outfile.flush();
outfile.close();

缓冲区和大小在其余代码中确定。
如何将文件放在特定路径中?

解决方案

在流的构造函数中指定完整路径,这可以是绝对路径或相对路径。 (相对于程序从哪里运行。



流析构函数关闭文件为你,显式关闭更可能引入错误(写入文件后关闭)。

  #include< fstream> 
#include< string>

int main()
{
const char * path =/ home / user / file.txt;
std :: ofstream file(path); //在构造函数中打开
std :: string data(data to write to file);
file<< data;
} //文件析构器
pre>

请注意,你可以在C ++ 11的文件构造函数中使用std :: string,在大多数情况下,它优先于const char *。


I have this code that writes successfully a file:

    ofstream outfile (path);
    outfile.write(buffer,size);
    outfile.flush();
    outfile.close();

buffer and size are ok in the rest of code. How is possible put the file in a specific path?

解决方案

Specify the full path in the constructor of the stream, this can be an absolute path or a relative path. (relative to where the program is run from.

The the streams destructor close the file for you, explicit closes are MORE likely to introduce bugs (writing to after the file is close).

#include <fstream>
#include <string>

int main()
{
    const char *path="/home/user/file.txt";
    std::ofstream file(path); //open in constructor
    std::string data("data to write to file");
    file << data;
}//file destructor

Note you can use std::string in the file constructor in C++11 and is preferred to a const char* in most cases.

这篇关于在C ++中的特定路径中写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆