How do I create a file with boost filesystem without opening it

天涯浪子 提交于 2021-02-18 21:54:05

问题


In boost filesystem there is a function create_directory which creates a directory. How do I create a file? I could create one by defining a boost::filesystem::ofstream object but that would also open the file, so I would have to call close on it before I could do other stuff to it, like renaming or deleting. Is this the only way?


回答1:


Boost Filesystem V3 doesn't provide a touch(1) function;

Even touch will creat+close a file, just look at the output of strace:

open("/tmp/q", O_WRONLY|O_CREAT|O_NOCTTY|O_NONBLOCK, 0666) = 47
dup2(47, 0)                             = 0
close(47)                               = 0
utimensat(0, NULL, NULL, 0)             = 0

I think your most reasonable bet is to just create a wrapper function that closes the file.




回答2:


You could just use something like

    // ... code ...
    boost::filesystem::ofstream( "/path/to/file" );
    boost::filesystem::rename( "/path/to/file", "/path/to/renamed_file" );
    // ... code ...

which will create an empty file and immediately rename it, without a need to close it at any point.



来源:https://stackoverflow.com/questions/30029343/how-do-i-create-a-file-with-boost-filesystem-without-opening-it

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