Search code examples
c++algorithmfiledirectoryfile-rename

How to change a text file's name in C++?


I would like to change a txt file's name, but I can not find how to do this.

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


Solution

  • #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.