Listing

Back

Listing 16.9: Using rename() to Change the Name of a Disk File
Code  1:
      2:
      3:
      4:
      5:
      6:
      7:
      8:
      9:
     10:
     11:
     12:
     13:
     14:
     15:
     16:
     17:
     18:
     19:
     20:
     21:
/* LIST1609.c: Day 16 Listing 16.9 */
/* Using rename() to change a filename. */
 
#include <stdio.h>
 
int main(void) {
  char oldname[80], newname[80];
  
  printf("Enter current filename: ");
  gets(oldname);
  printf("Enter new name for file: ");
  gets(newname);
  
  if (rename(oldname, newname) == 0)
    printf("%s has been renamed %s.",
           oldname, newname);
  else
    fprintf(stderr, "An error has occurred "
            "renaming %s.", oldname);
  return 0;
}
Output Enter current filename: list1609.exe
Enter new name for file: rname.exe
list1609.exe has been renamed rname.exe.
Description Listing 16.9 shows how powerful C can be. With only 18 lines of code, this program replaces a DOS command, and it's a much more friendly function.
Line 9 prompts for the name of the file to be renamed. Line 11 prompts for the new filename. The call to the rename() function is wrapped in an if statement on line 14. The if statement checks to ensure that the renaming of the file occurred correctly. If so, line 15 prints an affirmative message, otherwise  line 18 prints a message stating that there was an error.