How do i create a file in a sub directory in C++?

元气小坏坏 提交于 2019-12-11 10:36:01

问题


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();
}

回答1:


Specify the full path in the constructor:

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

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

Note:

  • 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().



回答2:


If you write the file path as "a" you are saving it in the same directory as the program. If you want it in the contacts directory (which will be in the the program's directory) you must write the path of the file. This directory will be /contacts/a, so your code should be:

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


来源:https://stackoverflow.com/questions/13935357/how-do-i-create-a-file-in-a-sub-directory-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!