简体   繁体   中英

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.

For example, I want to rename foo.txt to boo.txt in my C++ program.

#include <stdio.h> (or <cstdio> ) and use rename (or 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 isnotably 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).

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).

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

Boost::Filesystem is such C++ library that abstracts away platform differences.

You can use the Boost::Filesystem::rename to rename a file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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