home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / snip9707.zip / CHGEXT.C < prev    next >
C/C++ Source or Header  |  1997-07-05  |  2KB  |  84 lines

  1. /* +++Date last modified: 05-Jul-1997 */
  2.  
  3. /*
  4. **  chgext.c - Change a file's extension
  5. **
  6. **  public domain by Bob Stout
  7. **
  8. **  Arguments: 1 - Pathname
  9. **             2 - Old extension (NULL if don't care)
  10. **             3 - New extension
  11. **
  12. **  Returns: Pathname or NULL if failed
  13. **
  14. **  Note: Pathname buffer must be long enough to append new extension
  15. **
  16. **  Side effect: Converts Unix style pathnames to DOS style
  17. */
  18.  
  19. #include <stdio.h>
  20. #include <string.h>
  21. #include "filnames.h"
  22.  
  23. char *chgext(char *path, char *oldext, char *newext)
  24. {
  25.       char *p;
  26.  
  27.       /* Convert to DOS-style path name */
  28.  
  29.       for (p = path; *p; ++p)
  30.             if ('/' == *p)
  31.                   *p = '\\';
  32.  
  33.       /* Find extension or point to end for appending */
  34.  
  35.       if (NULL == (p = strrchr(path, '.')) || NULL != strchr(p, '\\'))
  36.             p = strcpy(&path[strlen(path)], ".");
  37.       ++p;
  38.  
  39.       /* Check for old extension */
  40.  
  41.       if (oldext && strcmp(p, oldext))
  42.             return NULL;
  43.  
  44.       /* Add new extension */
  45.  
  46.       while ('.' == *newext)
  47.             ++newext;
  48.       strncpy(p, newext, 3);
  49.  
  50.       /*
  51.       ** Added to insure string is properly terminated. Without this, if
  52.       ** the new extension is longer than the old, we lose the terminator.
  53.       */
  54.  
  55.       p[strlen(newext)] = '\0';
  56.  
  57.       return path;
  58. }
  59.  
  60. #ifdef TEST
  61.  
  62. main(int argc, char *argv[])
  63. {
  64.       char *retval, *old_ext = NULL, path[128];
  65.  
  66.       if (2 > argc)
  67.       {
  68.             puts("Usage: CHGEXT path [old_ext]");
  69.             puts("\nChanges extension to \".TST\"");
  70.             puts("Old extension optional");
  71.             return -1;
  72.       }
  73.       strcpy(path, strupr(argv[1]));
  74.       if (2 < argc)
  75.             old_ext = strupr(argv[2]);
  76.       if (NULL == (retval = chgext(path, old_ext, ".TSTstuff")))
  77.             puts("chgext() failed");
  78.       else  printf("chgext(%s, %s, TST)\n...returned...\n%s\n", argv[1],
  79.             old_ext ? old_ext : "NULL", path);
  80.       return (NULL == retval);
  81. }
  82.  
  83. #endif /* TEST */
  84.