How do I rename an existing file using c++

How do I rename an existing file using c++??
is there any function in fstream ??



Thanks in advanced.
Use the rename() function in <cstdio>

http://www.cplusplus.com/reference/cstdio/rename/
@Chervil

I have read that, but how do I access the source folder?

I m using codeblocks and I want to change the name of a text file which is in Project folder.

Well, it works for me when I use code::blocks on windows.

Depending on your system configuration and the way you run the program, then the program may default to using the same folder as the executable (.exe program) for the current working directory.

On my system, the executable is nested two levels deep inside folder bin\Debug. The first step would be to check what is the current working directory.

If necessary you might then either change the program's current working directory, or alternatively change the text of the file name to specify the required path.

This code is for windows. It displays the current working directory. Then attempts to change to one level higher:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <string>
#include <windows.h>

using namespace std;

std::string getDir()
{
    char buff[MAX_PATH];
    if ( GetCurrentDirectoryA(MAX_PATH, buff) )
        return buff;
        
    cout << "get directory failed\n";
    return "";
}

int main()
{
    cout << "Current dir: " <<  getDir() << '\n';   
    

    if ( SetCurrentDirectoryA("../") )
        cout << "Directory change ok\n";
    else
        cout << "Directory change failed\n";

        
    cout << "Current dir: " <<  getDir() << '\n';   
        
}
Last edited on
for this sort of thing, if it isnt portable code, I often just let the OS do it by calling mv (unix) or ren (windows) through the shell (system() or any of a half dozen others).
Thanks man , You are awesome :) :)
Topic archived. No new replies allowed.