Namespaces
Variants
Views
Actions

std::rename

From cppreference.com
< cpp‎ | io‎ | c
 
 
Input/output library
I/O manipulators
C-style I/O
Buffers
(deprecated in C++98)
Streams
Abstractions
File I/O
String I/O
Array I/O
(deprecated in C++98)
(deprecated in C++98)
(deprecated in C++98)
Synchronized Output
Types
Error category interface
(C++11)
 
 
Defined in header <cstdio>
int rename( const char *old_filename, const char *new_filename );

Changes the filename of a file. The file is identified by character string pointed to by old_filename. The new filename is identified by character string pointed to by new_filename.

If new_filename exists, the behavior is implementation-defined.

Contents

[edit] Parameters

old_filename - pointer to a null-terminated string containing the path identifying the file to rename
new_filename - pointer to a null-terminated string containing the new path of the file

[edit] Return value

0 upon success or non-zero value on error.

[edit] Notes

POSIX specifies many additional details on the semantics of this function, which are reproduced in C++ by std::filesystem::rename.

[edit] Example

#include <iostream>
#include <fstream>
#include <cstdio>
int main()
{
    bool ok{std::ofstream("from.txt").put('a')}; // create and write to file
    if (!ok) {
        std::perror("Error creating from.txt");
        return 1;
    }
 
    if (std::rename("from.txt", "to.txt")) {
        std::perror("Error renaming");
        return 1;
    }
 
    std::cout << std::ifstream("to.txt").rdbuf() << '\n'; // print file
}

Output:

a

[edit] See also

(C++17)
moves or renames a file or directory
(function) [edit]
erases a file
(function) [edit]
C documentation for rename