如何在 C++ 中更改文本文件的名称
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6103036/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to change a text file's name in C++
提问by Jail
I'd like to change a txt
file's name but I can't find how to do this.
我想更改txt
文件名,但找不到如何执行此操作。
For example, I want to rename foo.txt
to boo.txt
in my C++ program.
例如,我想在我的 C++ 程序中重命名foo.txt
为boo.txt
。
回答by Jerry Coffin
#include <stdio.h>
(or <cstdio>
) and use rename
(or std::rename
):
#include <stdio.h>
(或<cstdio>
)并使用rename
(或std::rename
):
rename("oldname.txt", "newname.txt");
Contrary to popular belief, this is included in the standard library, and is portable up to a point -- though of course the allowable contents of the strings will vary with the target system.
与流行的看法相反,这包含在标准库中,并且在一定程度上是可移植的——当然,字符串的允许内容会因目标系统而异。
回答by Tamás Szelei
Filesystem support is notably absent from the C++ standard library. As Jerry Coffin's answer shows, there actually is a rename function in stdio (contrary to the popular belief which I shared). There are however many filesystem-related appliances that the standard lib does not cover, hence the existence of Boost::Filesystem (notably manipulating directories and retrieving information about files).
文件系统支持是 在 C++ 标准库中明显不存在. 正如 Jerry Coffin 的回答所示,stdio 中实际上有一个重命名函数(与我分享的流行观点相反)。然而,标准库没有涵盖许多与文件系统相关的设备,因此存在 Boost::Filesystem(特别是操作目录和检索有关文件的信息)。
This is a design decision to make C++ less constrained (i.e. make it possible to compile on a wide range of platforms including embedded systems where the idea of a file is non-existent).
这是使 C++ 不受约束的设计决策(即,可以在各种平台上进行编译,包括不存在文件概念的嵌入式系统)。
To perform file operations, one has two options:
要执行文件操作,有两个选项:
Use the API of the target OS
Use a library that provides a unified interface across platforms
使用目标操作系统的 API
使用提供跨平台统一接口的库
Boost::Filesystemis such C++ library that abstracts away platform differences.
Boost::Filesystem就是这样一个抽象出平台差异的 C++ 库。
You can use the Boost::Filesystem::renameto rename a file.
您可以使用Boost::Filesystem::rename重命名文件。