File "rename" still broken?

21 Jun 2011

I notice a thread in which Thomas Hamilton was working on fixing the FATFileSystem "rename" function. What was the final resolution on the function? I see the thread ended in August 2010 without further comment. The latest FATFileSystem I downloaded & compiled today still has the broken "rename" function. Simon Ford, did you ever get a chance to look into this?

I guess one could open a new file with the new desired filename, do a byte-to-byte copy, close the files, and delete the old file.

Thanks, Doug Wendelboe

22 Jun 2011

I coded up a function called file_rename which does the same job as the broken rename() function. Excuse the hoakeyness in that instead of just renaming the directory entry, the function copies the original file to a new file created with the new desired name. The function then reopens the new file to insure that it was actually created as the renamed file. If the new file is OK, the old file is deleted.

//***********************************************************
// file_rename: renames a file.
//    Kind of hoakey as it moves data instead of adjusting
//    the file name in the directory. 
//    Checks to insure the file was renamed.
//    Returns -1 = error; 0 = success
//***********************************************************
int file_rename(const char *oldfile, const char *newfile) {
    int retval = 0;
    int ch;

    FILE *fpold = fopen(oldfile, "r");
    FILE *fpnew = fopen(newfile, "w");
    
    while (1) {  
        ch = fgetc(fpold); 
        if (ch == EOF) break;
        fputc(ch, fpnew);  
    }
    
    fclose(fpnew);
    fclose(fpold);

    fpnew = fopen(newfile, "r");
    if(fpnew == NULL) {
        retval = (-1);
    } 
    else {
        remove(oldfile);
    }
    fclose(fpnew);
    return (retval);
}

Out of this same code a file_copy fell out. It is just the same code above but the old file is not deleted. Same error checking occurs.

//***********************************************************
// file_copy: Copies a file
//            Checks to insure destination file was created.
//            Returns -1 = error; 0 = success
//***********************************************************
int file_copy(const char *oldfile, const char *newfile) {
    int retval = 0;
    int ch;

    FILE *fpold = fopen(oldfile, "r");
    FILE *fpnew = fopen(newfile, "w");
    
    while (1) {  
        ch = fgetc(fpold); 
        if (ch == EOF) break;
        fputc(ch, fpnew);  
    }
    
    fclose(fpnew);
    fclose(fpold);    

    fpnew = fopen(newfile, "r");
    if(fpnew == NULL) {
        retval = (-1);
    } 
    fclose(fpnew);
    return (retval);
}