如何在不打开文件的情况下使用boost文件系统创建文件

时间:2021-08-24 20:21:08

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?

在boost文件系统中,有一个create_directory函数可以创建一个目录。如何创建文件?我可以通过定义一个boost :: filesystem :: ofstream对象来创建一个,但是也可以打开文件,所以在我可以做其他事情之前我必须调用close,比如重命名或删除。这是唯一的方法吗?

2 个解决方案

#1


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

Boost Filesystem V3不提供touch(1)功能;

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

甚至触摸都会创建+关闭文件,只需查看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.

这将创建一个空文件并立即重命名,而无需在任何时候关闭它。

#1


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

Boost Filesystem V3不提供touch(1)功能;

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

甚至触摸都会创建+关闭文件,只需查看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.

这将创建一个空文件并立即重命名,而无需在任何时候关闭它。