0

I have the below code and for some reason, rename(..) function is failing. I have tried supplying full paths, as well as changing working directory and then supplying just filenames. Below is the latter which fails and errno is 13. All files are in my Projects folder of this win32 console project. I don't understand why it is so difficult to simply change a filename, regardless of what the current working dir is.

//fname_string* points to beginning of actual filename
//filename contains entire output file path
//file_ext* points to .csv portion
//fname will get old filename
fname_string = strrchr( filename, '\\' );
if( fname_string == NULL )
{
    fname_string = filename;    //no dir supplied, so set it to filename
}
else
{
    strncpy( fname, filename, fname_string - filename );
    fname[fname_string-filename] = '\0';
    chdir(fname);
    fname_string++; //now points to filename
    read_success = errno; //this succeeds supposedly
}

strcpy( fname, fname_string );  //save old file path
sprintf( file_ext, "_%d.csv", append_esn ); //append_esn = 1234
read_success = rename( fname, fname_string );
read_success = errno;  //giving me 13

EDIT: I'm dumb and I was closing the 'input' file, and not the 'output' file. So FYI, file better be closed! The reason why I thought it was closed is because I flush the output file and sometimes it didn't have a zero size file.

So rename can take a full path or just the filenames if its in the working directory...There goes two hours of nonsense.... So the above would work, or just doing the below assuming same pointers mentioned above:

strcpy( fname, filename );  //save old file path
sprintf( file_ext, "_%d.csv", append_esn );
read_success = rename( fname, filename );
NickG
  • 871
  • 3
  • 11
  • 18
  • Did you try printing the filenames right before `rename` ? – cnicutar Feb 22 '12 at 21:41
  • I'm currently debugging, and when hovering over them, fname = log.csv and fname_string is log_1234.csv A similar question is here [link](http://stackoverflow.com/questions/4512256/win32-api-for-rename-a-file-in-c) that I may look into – NickG Feb 22 '12 at 21:43
  • You should **only** check errno if rename() returns -1. – wildplasser Feb 22 '12 at 21:48
  • Just before it, I do have it open, but I call fclose( input ) which is the file that I was changing....if that helps. – NickG Feb 22 '12 at 22:00
  • I was able to get it to work if I manually copied the files to the c drive and chdir to ("C:\\"). This leads me to believe that this has something to do with my slashes in the strings. I believe they are currently being passed in as just C:\Docume.... with only one slash. Is there a way to guarantee the slashes are a certain way? or perhaps replace single slashes with double slashes? – NickG Feb 22 '12 at 22:28

1 Answers1

0

My last comment above answers this question/issue.

NickG
  • 871
  • 3
  • 11
  • 18