简体   繁体   English

如何在 C++ 中更改文本文件的名称

[英]How to change a text file's name in C++

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

#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.与普遍的看法相反,它包含在标准库中,并且在一定程度上是可移植的——当然,字符串的允许内容会随着目标系统的不同而变化。

Filesystem support is文件系统支持是notably absent from the C++ standard library C++ 标准库中明显没有. . As Jerry Coffin's answer shows, there actually is a rename function in stdio (contrary to the popular belief which I shared).正如 Jerry Coffin 的回答所示,实际上在 stdio 中有一个重命名 function (与我分享的普遍看法相反)。 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).然而,标准库没有涵盖许多与文件系统相关的设备,因此存在 Boost::Filesystem(特别是操作目录和检索有关文件的信息)。

This is a design decision to make C++ less constrained (ie 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使用目标操作系统的API

  • Use a library that provides a unified interface across platforms使用提供跨平台统一接口的库

Boost::Filesystem is such C++ library that abstracts away platform differences. Boost::Filesystem就是这样的 C++ 库,它抽象了平台差异。

You can use the Boost::Filesystem::rename to rename a file.您可以使用Boost::Filesystem::rename 重命名文件。

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

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