如何确保 boost::文件系统::remove 不会尝试删除由其他进程使用的文件

How to be sure that boost::filesystem::remove does not try to delete a file that is used by another process?

本文关键字:删除 其他 进程 文件 确保 何确保 boost remove 文件系统      更新时间:2023-10-16

我想将文件上传到 AWS S3 存储桶。在执行此操作之前,我从中创建.gz文件以减少其存储。上传后,我想再次使用 boost::文件系统::删除删除.gz文件。

似乎上传正在

阻止它正在上传的文件,我无法找到等待完整结果的方法,因此文件不再被锁定。

删除与 main() 中的不同调用一起工作。上传调用后,它立即不起作用,并且 boost operations.hpp 会引发异常。

异常表示该文件已被另一个进程使用。

int main(int argc, char *argv[])
{
boost::filesystem::path path{ C:/Development/test.gz };
//deletes the file correctly if called
//boost::filesystem::remove(path); 
//upload file first, then delete it
putObject(path)
}
void putObject(path, s3client)
{
auto input_data = Aws::MakeShared<Aws::FStream>("", path.string(),
std::ios_base::in | std::ios_base::binary);
auto request = Aws::S3::Model::PutObjectRequest();
request.WithBucket("bucketName").WithKey(key);
request.SetBody(input_data);
request.SetMetadata(metadata);
    //upload file to s3 bucket
s3client->PutObject(request);
//throws exception if called - file is in use
boost::filesystem::remove(path);
}

引发异常的 boost operations.hpp(第 664 行):

inline
// For standardization, if the committee doesn't like "remove", consider  
"eliminate"
bool remove(const path& p)           {return detail::remove(p);}

有没有办法确保如果文件不再被阻止,该文件将被删除?

当您尝试删除该文件时,您的 Aws::FStream 仍处于打开状态。 因此,您只需要在尝试删除它之前关闭它。

我想你可以简单地打电话

input_data->close();

在删除文件之前。