Rename File

Jan 20, 2012 at 11:15pm
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 Jan 20, 2012 at 11:15pm
Jan 20, 2012 at 11:23pm
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
Jan 20, 2012 at 11:25pm
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 Jan 20, 2012 at 11:25pm
Jan 20, 2012 at 11:25pm
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.
Jan 21, 2012 at 12:25am
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.
Jan 21, 2012 at 4:07pm
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 Jan 21, 2012 at 4:09pm
Jan 21, 2012 at 6:10pm
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.