Problems with rename()

So, upon trying to help someone else with their file renaming, I ran into an issue as well. Here's a link to the other thread
http://www.cplusplus.com/forum/beginner/59833/#msg323137

Ok so I wrote up a quick program to see what could be going on, and realized that I also cannot rename a file.
1
2
3
4
5
6
7
8
int result;
  fstream test;
  test.open("oldname.txt");
  result= rename( "oldname.txt" , "newname.txt" );
  if ( result == 0 )
    puts ( "File successfully renamed" );
  else
    perror( "Error renaming file" );


Error I'm getting is
No such file or directory.

So that sounds like to me that the file is never being created. So I was thinking, maybe the default write permissions of fstream wouldn't allow renaming, so I looked into write permissions, and didn't see any that sound related. And I believe fstream has default read/write permissions anyways.

So, what is going on here? I'm stumped

EDIT:
I just tried manually creating a file before execution, and I still got the same error message. Bleh
Last edited on
Try closing the stream before renaming the file.
test.close();
Well, I tried this as my second approach. This was when I created a file manually.
1
2
3
4
5
6
7
int result;
  result= rename( "test.txt" , "newname.txt" );
  if ( result == 0 )
    puts ( "File successfully renamed" );
  else
    perror( "Error renaming file" );
  cin.get();


I never even open a stream here and I get the same message
I think @Peter is right.
Check
http://www.cplusplus.com/reference/clibrary/cstdio/rename/
where it says
This is an operation performed directly on a file; No streams are involved in the operation.
I have no streams at all in my second attempt
Are you sure files is in the correct directory? Sometimes IDEs sets the working directory to something special.
Oh wow, yea just moved it and it worked fine. Thanks!
So that sounds like to me that the file is never being created.
Yep "oldname.txt" doesn't exists, as you are openning as input/ouput it will not be created.
So if I open as fstream, it will not create the file if it doesnt exist?
Topic archived. No new replies allowed.