如何在C ++的子目录中创建文件? [英] How do i create a file in a sub directory in C++?

查看:112
本文介绍了如何在C ++的子目录中创建文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码,如何在子目录联系人中创建文件?每次创建文件时,它就会出现在与我的程序相同的目录中.

Here is my code, how do i create a file in the sub directory contacts? Every time the file is created, it appears in the same directory as my program.

int main(){
ofstream myfile("\\contacts");
myfile.open ("a");
myfile.close();
}

推荐答案

在构造函数中指定完整路径:

Specify the full path in the constructor:

ofstream myfile(".\\contacts\\a"); // or just "contacts/a"
if (myfile.is_open())
{
}

发布的代码尝试创建一个名为"\\contacts"的文件,然后创建另一个名为"a"的文件.

The posted code attempts to create a file called "\\contacts" and then another file called "a".

注意:

  • ofstream不会创建中间目录:"contacts"必须在使用ofstream之前存在.
  • 析构函数将关闭ofstream,因此无需显式调用myfile.close().
  • that ofstream will not create intermediate directories: "contacts" must exist prior to the use of the ofstream.
  • the destructor will close the ofstream so it is unnecessary to explicitly call myfile.close().

这篇关于如何在C ++的子目录中创建文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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