Rename File

Im trying to rename my file to the new name that the user has shown but i get a error. here is the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int StoreDatabase()
{
    string FileName;
    LetterByLetter Print;
    ofstream StoreInDatabase("Main_Database.txt");
    system("cls");
    DisplayText = "What would you like to name the new text file?";
    Print.Text();
    cin >> FileName;
    string NewName;
    string extention;
    extention = ".txt";
    NewName = FileName + extention;
    rename("Main_Database.txt",NewName);
    system("PAUSE");
}
Last edited on
1
2
3
4
  int result;
  char oldname[] ="oldname.txt";
  char newname[] ="newname.txt";
  result= rename( oldname , newname );


On a side note, is this a function...?
If so, it's a doing bit much for one function. Also, you're missing your return statement
std::rename takes c strings as argument so you have to convert the std::string to a c string by using the c_str() member function
rename("Main_Database.txt",NewName.c_str());
Last edited on
http://www.cplusplus.com/forum/articles/40071/#msg216270
If there is a runtime error, check the returned values. perror() will give you an alusive message.
Peter87 i tried this, it doesn't give me errors but it doesn't rename the file to what the user inputs and yes it is a function.
Are you checking for perror()?
1
2
3
4
5
6
result= rename( oldname , newname );
  if ( result == 0 )
    puts ( "File successfully renamed" );
  else
    perror( "Error renaming file" );
  cin.get();


This will tell you whats wrong

Edit:
Result is just an int.
Could change it to
if(rename(oldname,newname) != 0)
Last edited on
Alright so I did some messing around and asking around. Make sure your stream is closed before you attempt to rename, and also make sure the file is in the right directory.

So for you, before you call rename(), call StoreInDatabase.close()
Topic archived. No new replies allowed.