简体   繁体   English

如何在 C++ 中创建临时文本文件?

[英]How to create a temporary text file in C++?

I'm trying to create a temporary text file in C++ and then delete it at the end of the program.我正在尝试用 C++ 创建一个临时文本文件,然后在程序结束时将其删除。 I haven't had much luck with Google.我对谷歌的运气并不好。

Could you tell me which functions to use?你能告诉我使用哪些功能吗?


The answers below tell me how to create a temp file.下面的答案告诉我如何创建临时文件。 What if I just want to create a file (tmp.txt) and then delete it?如果我只想创建一个文件 (tmp.txt) 然后将其删除怎么办? How would I do that?我该怎么做?

Maybe this will help也许这会有所帮助

FILE * tmpfile ( void );

http://www.cplusplus.com/reference/clibrary/cstdio/tmpfile/ http://www.cplusplus.com/reference/clibrary/cstdio/tmpfile/

Open a temporary file打开临时文件

Creates a temporary binary file, open for update (wb+ mode -- see fopen for details).创建一个临时二进制文件,打开以进行更新(wb+ 模式——有关详细信息,请参阅 fopen)。 The filename is guaranteed to be different from any other existing file.文件名保证与任何其他现有文件不同。 The temporary file created is automatically deleted when the stream is closed (fclose) or when the program terminates normally.创建的临时文件在流关闭(fclose)或程序正常终止时自动删除。

See also也可以看看

char * tmpnam ( char * str );

Generate temporary filename生成临时文件名

A string containing a filename different from any existing file is generated.生成一个包含与任何现有文件不同的文件名的字符串。 This string can be used to create a temporary file without overwriting any other existing file.此字符串可用于创建临时文件而不会覆盖任何其他现有文件。

http://www.cplusplus.com/reference/clibrary/cstdio/tmpnam/ http://www.cplusplus.com/reference/clibrary/cstdio/tmpnam/

Here's a complete example:这是一个完整的例子:

#include <unistd.h>

int main(void) {
  char filename[] = "/tmp/mytemp.XXXXXX"; // template for our file.        
  int fd = mkstemp(filename);    // Creates and opens a new temp file r/w.
                                 // Xs are replaced with a unique number.
  if (fd == -1) return 1;        // Check we managed to open the file.
  write(fd, "abc", 4);           // note 4 bytes total: abc terminating '\0'
  /* ...
     do whatever else you want.
     ... */
  close(fd);
  unlink(filename);              // Delete the temporary file.
}

If you know the name of the file you want to create (and are sure it won't already exist) then you can obviously just use open to open the file.如果您知道要创建的文件的名称(并且确定它不存在),那么您显然可以使用open打开该文件。

tmpnam and tmpfile should probably be avoided as they can suffer from race conditions - see man tmpfile(3) for the details. tmpnamtmpfile可能应该避免使用,因为它们可能会受到竞争条件的影响 - 有关详细信息,请参阅man tmpfile(3)

This may be a little off-topic because the author wanted to create a tmp.txt and delete it after using it, but that is trivial - you can simple open() it and delete it (using boost::filesystem of course).这可能有点跑题,因为作者想创建一个 tmp.txt 并在使用后将其删除,但这很简单——您可以简单地 open() 并删除它(当然使用 boost::filesystem)。

mkstemp() is UNIX-based. mkstemp() 是基于 UNIX 的。 With Windows you use GetTempFileName() and GetTempPath() to generate a path to a temp file.在 Windows 中,您使用 GetTempFileName() 和 GetTempPath() 生成临时文件的路径。 Sample code from MSDN:来自 MSDN 的示例代码:

http://msdn.microsoft.com/en-us/library/aa363875%28VS.85%29.aspx http://msdn.microsoft.com/en-us/library/aa363875%28VS.85%29.aspx

On Linux (starting with kernel 3.11), there's flag to open(2) O_TMPFILE that creates a temporary file that doesn't have a name (ie it doesn't show up in the filesystem).在 Linux(从内核 3.11 开始)上,有 open(2) O_TMPFILE 标志创建一个没有名称的临时文件(即它不会出现在文件系统中)。 This has a few interesting features:这有几个有趣的特点:

  • No worries about unique names, it's just an inode, there is no name.不用担心唯一名称,它只是一个 inode,没有名称。
  • No race conditions during creation (eg symlink attacks).创建期间没有竞争条件(例如符号链接攻击)。
  • No stray files if your app crashes, it's always automatically deleted.如果您的应用程序崩溃,没有杂散文件,它总是会自动删除。

If you need a named file (for example, so you can pass the name to another process, perhaps a compiler or editor), then register a cleanup function that removes the file with atexit() .如果您需要一个命名文件(例如,您可以将名称传递给另一个进程,可能是编译器或编辑器),则注册一个使用atexit()删除文件的清理函数。 You can use either C++ <iostream> or C FILE * ( <cstdio> ) to create the file.您可以使用 C++ <iostream>或 C FILE * ( <cstdio> ) 创建文件。 The not completely standard but widely available mkstemp() function creates a file and tells you its name as well as returning a file descriptor (a third I/O mechanism);不完全标准但广泛使用的mkstemp()函数创建一个文件并告诉您它的名称并返回一个文件描述符(第三种 I/O 机制); you could use the fdopen() function to convert the file descriptor into a FILE * .您可以使用fdopen()函数将文件描述符转换为FILE *

If you don't need a named file a C-style FILE * is OK, then look at tmpfile() as suggested by @Tom.如果您不需要命名文件,则 C 样式的FILE *就可以了,然后按照@Tom 的建议查看tmpfile()

I wonder why most of you guys showed him the C way of doing it instead of the C++ way.我想知道为什么你们中的大多数人向他展示了 C 的方式而不是 C++ 的方式。
Here's fstream .这是fstream
Try that, deleting a file is OS depended but you can use boost.filesystem to make things easy for you.试试看,删除文件取决于操作系统,但您可以使用boost.filesystem使事情变得容易。

Well, assuming you have been successful in creating the temporary file, you can use the remove function to delete it.那么,假设您已经成功创建了临时文件,您可以使用删除功能将其删除。

The function is declared in stdio.h -该函数在 stdio.h 中声明 -

#include <stdio.h>

int remove(const char *pathname);

For example, if you want to delete a file named myfile.txt the code will be例如,如果您要删除名为 myfile.txt 的文件,代码将是

#include<stdio.h>

int main()
{
  if(remove("myfile.txt") == -1)
  {
    fprintf(stderr,"Remove failed");
    exit(EXIT_FAILURE);
  }
  exit(EXIT_SUCCESS);
}

I hope by now, you already know how to create the temp file, so this should resolve your query.我希望现在您已经知道如何创建临时文件,因此这应该可以解决您的查询。 Hope it helps.希望能帮助到你。

Boost提供了一种干净、可移植且不被弃用的创建临时文件的方法:

auto temporary_file = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM