summaryrefslogtreecommitdiff
path: root/reference/C/CONTRIB/SNIP/chgext.c
blob: b394572ebf3271ab76b56a583fde69615c7545ba (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/*
**  chgext.c - Change a file's extension
**
**  public domain by Bob Stout
**
**  Arguments: 1 - Pathname
**             2 - Old extension (NULL if don't care)
**             3 - New extension
**
**  Returns: Pathname or NULL if failed
**
**  Note: Pathname buffer must be long enough to append new extension
**
**  Side effect: Converts Unix style pathnames to DOS style
*/

#include <stdio.h>
#include <string.h>

char *chgext(char *path, char *oldext, char *newext)
{
      char *p;

      /* Convert to DOS-style path name */

      for (p = path; *p; ++p)
            if ('/' == *p)
                  *p = '\\';

      /* Find extension or point to end for appending */

      if (NULL == (p = strrchr(path, '.')) || NULL != strchr(p, '\\'))
            p = strcpy(&path[strlen(path)], ".");
      ++p;

      /* Check for old extension */

      if (oldext && strcmp(p, oldext))
            return NULL;

      /* Add new extension */

      while ('.' == *newext)
            ++newext;
      strncpy(p, newext, 3);
      return path;
}

#ifdef TEST

void main(int argc, char *argv[])
{
      char *retval, *old_ext = NULL, path[128];

      if (2 > argc)
      {
            puts("Usage: CHGEXT path [old_ext]");
            puts("\nChanges extension to \".TST\"");
            puts("Old extension optional");
            return;
      }
      strcpy(path, strupr(argv[1]));
      if (2 < argc)
            old_ext = strupr(argv[2]);
      if (NULL == (retval = chgext(path, old_ext, ".TSTstuff")))
            puts("chgext() failed");
      else  printf("chgext(%s, %s, TST)\n...returned...\n%s\n", argv[1],
            old_ext ? old_ext : "NULL", path);
}

#endif /* TEST */