Rename LocalFileSystem flash memory files, thanks Doug Wendelboe for the fix

Dependencies:   mbed

rename.h

Committer:
mbed2f
Date:
2012-04-02
Revision:
0:07f9467c9d46

File content as of revision 0:07f9467c9d46:

  //***********************************************************
// file_rename: renames a file (via copy & delete).
//    Moves data instead of adjusting the file name in the
//    file directory. Checks to insure the file was renamed.
//    Returns -1 = error; 0 = success
//***********************************************************
int file_rename(const char *oldfname, const char *newfname) {
    int retval = 0;
    int ch;

    FILE *fpold = fopen(oldfname, "r");   // src file
    FILE *fpnew = fopen(newfname, "w");   // dest file
    
    while (1) {                   // Copy src to dest  
        ch = fgetc(fpold);        // until src EOF read. 
        if (ch == EOF) break;
        fputc(ch, fpnew);  
    }
    
    fclose(fpnew);
    fclose(fpold);

    fpnew = fopen(newfname, "r"); // Reopen dest to insure
    if(fpnew == NULL) {           // that it was created.
        retval = (-1);            // Return Error.
    } 
    else {
        fclose(fpnew);  
        remove(oldfname);         // Remove original file.
        retval = (0);             // Return Success.
    }
    return (retval);
}

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

    FILE *fpsrc = fopen(src, "r");   // src file
    FILE *fpdst = fopen(dst, "w");   // dest file
    
    while (1) {                  // Copy src to dest
        ch = fgetc(fpsrc);       // until src EOF read.
        if (ch == EOF) break;
        fputc(ch, fpdst);  
    }
    fclose(fpsrc);  
    fclose(fpdst);
  
    fpdst = fopen(dst, "r");     // Reopen dest to insure
    if(fpdst == NULL) {          // that it was created.
        retval = (-1);           // Return error.
    } 
    else {
        fclose(fpdst); 
        retval = (0);            // Return success.
    }
    return (retval);
}