std::rename(3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

πŸ’… NAME πŸ’…

std::rename - std::rename β€” okay so the name is literally std::rename and the one-liner is also std::rename. Minimalist queen behavior. This is the std::rename(3) page from the C++ Standard Libary manual, section 3, and we're gonna get you comfy with it, bestie 🫢.


✨ Synopsis ✨

Defined in header <cstdio>.

int rename( const char* old_filename, const char* new_filename );

So what does it do? It changes the filename of a file. The file is identified by the character string pointed to by old_filename. The new filename is identified by the character string pointed to by new_filename.

And if new_filename already exists? Behavior is implementation-defined β€” so not universal, check your implementation, no cap. Implementation-defined is the vibe check you don't skip.


πŸŽ€ Parameters πŸŽ€

  • old_filename β€” a pointer to a null-terminated string containing the path identifying the file to rename. That's your "before" path, bestie.
  • new_filename β€” a pointer to a null-terminated string containing the new path of the file. That's your "after" path, slay.

πŸ’– Return value πŸ’–

Returns 0 upon success, or a non-zero value on error. That's the whole story. 0 = iconic, non-zero = something went off.


πŸ¦‹ Notes πŸ¦‹

POSIX specifies many additional details on the semantics of this function, and those details are reproduced in C++ by std::filesystem::rename. So if you want the full deep lore, that's your next stop, iykyk.


πŸ”₯ Example πŸ”₯

Here's the example, literally verbatim. It even starts with // Run this code because that's what the page says, bestie.

// Run this code

#include <cstdio>
#include <cstdlib>
#include <fstream>
#include <iostream>

int main()
{
    if (!std::ofstream("from.txt").put('a')) // create and write to file
    {
        std::perror("Error creating from.txt");
        return EXIT_FAILURE;
    }

    if (std::rename("from.txt", "to.txt"))
    {
        std::perror("Error renaming");
        return EXIT_FAILURE;
    }

    std::cout << std::ifstream("to.txt").rdbuf() << '\n'; // print file
    return EXIT_SUCCESS;
}

⭐ Output ⭐

And the output is literally:

a

🌈 See also 🌈

  • rename β€” moves or renames a file or directory (C++17) (function)
  • remove β€” erases a file (function)
  • C documentation for rename

That's the page, bestie! Shoutout to the source http://cppreference.com, the version/date 2024.06.10, and this very iconic std::rename(3) page. Mwah πŸ’‹βœ¨

πŸ“¦ where this page comes from