在Windows中从纯C创建唯一的临时目录 [英] Creating a unique temporary directory from pure C in windows

查看:145
本文介绍了在Windows中从纯C创建唯一的临时目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Windows中使用某些C语言创建一个唯一的临时目录 代码(不是C ++或C#).我想这样做,这样我可以放一些温度 目录中的文件,然后在完成后轻松将其全部删除 (通过递归删除目录).

I'd like to create a unique temporary directory in Windows from some C code (not C++ or C#). I want to do this so that I can put some temp files in the directory, and then delete them all easily when I'm done (by removing the directory recursively).

我本质上是在寻找与Linux相当的产品 mkdtemp 功能.在此处中有一个C#答案,并且对

I'm essentially looking for an equivalent of the linux mkdtemp function. There is a C# answer here, and responses on this question suggest using Boost. But since I'm using C, those solutions don't work for me.

到目前为止,我能想到的最好的方法就是使用 GetTempFileName 然后是 CreateDirectory , 但问题是,如果我问 GetTempFileName 创建一个唯一的文件名,它还将创建该文件( 不需要,因为我想创建一个目录).

The best I've been able to come up with so far is to use GetTempFileName followed by CreateDirectory, but the problem there is that if I ask GetTempFileName to create a unique file name, it will also create the file (which I don't want, since I want to make a directory instead).

相关地, GetTempPath , 从环境返回用户的临时文件夹的位置 变量-但由于我想创建自己的目录,因此我可以 以后安全删除,我仍然需要在任何目录下创建目录 返回的路径.

Relatedly, there's GetTempPath, which returns the location of the user's temp folder from environment variables - but since I want to create my own directory that I can safely delete later, I still need to create a directory inside any path it would return.

如果我想创建一个唯一目录,则必须 创建一个临时文件,获取名称,将其删除,然后创建一个 具有相同名称的目录-听起来很混乱. 还有其他想法吗?

It looks like if I want a unique directory to be created, I'll have to create a temp file, get the name, delete it, and then create a directory with the same name - which sounds very messy. Any other ideas?

推荐答案

您可以使用GetTempPath返回的值与Guid并置,以确保目录的唯一性.您可以使用 UuidCreate 或 CoCreateGuid函数.

You can use what GetTempPath returns concatenated with a Guid to ensure uniqueness of the directory. You can create a Guid using UuidCreate or CoCreateGuid Function.

要递归删除目录,这里有一个纯C语言示例:如何删除递归目录?基于FindFirstFile,FindNextFile,DeleteFile和 RemoveDirectory a>.

To delete recursively the directory, there is an example here in pure C: How to remove directory recursively? based on FindFirstFile, FindNextFile, DeleteFile and RemoveDirectory.

还有 SHFileOperation 但它更重,并且基于Windows Shell函数,并且并非总是需要Shell DLL,尤其是在编写服务器代码的情况下.

There is also SHFileOperation but it's more heavyweight and is based on the Windows Shell functions, and the Shell DLLs are not always wanted, especially if you're writing server code.

这篇关于在Windows中从纯C创建唯一的临时目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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