Listing 3

/*
 *  RET.C: Return to previous working directory
 *  Written by Leor Zolman, 9/89
 *
 *      (companion to CDE.C)
 *  Uses the Master Environment package from CUJ 7/89
 *
 *  Usage:
 *    ret                   (returns to previous directory)
 *
 *  Compile/Link:
 *      cl /Ox ret.c util.c envlib  (ENVLIB.OBJ is Master Environment pkg)
 */

#include   <stdio.h>
#include   <string.h>
#include   <stdlib.h>
#include   <dos.h>
#include   "util.h"

main(int argc, char **argv)
{

    char  *pathp;
    char  cwdbuf[MAX_DIRNAME_SIZE];

    int      chaincnt;
    char     chnevar1[MAX_EVARNAME_SIZE],   /* env var names built here   */
            chnevar2[MAX_EVARNAME_SIZE];
    char     chndname_save[MAX_DIRNAME_SIZE], *chndname;
    char     itoabuf[10];                    /* used by itoa() function   */
    int i;

                        /* Get current dir. name and current drive: */
    getcwd(cwdbuf, MAX_DIRNAME_SIZE);

    if (argc != 1)
       error("Usage: ret     (returns to last dir cde'd from)");

    if ((pathp = m_getenv(CHAINS_VAR)) == NULL)
        error("cde hasn't been run yet");
    else
        chaincnt = atoi(pathp);

                              /* See if CDE has created any entries: */
    strcpy(chnevar1, CHAIN_BASE);
    strcat(chnevar1, "1");
    if (!(pathp = m_getenv(chnevar1)))   /* if so, pathp points to last dir  */
        error("No previous directory"); /* else no previous dir   */

    change_dir(pathp);                   /* change to previous directory:   */

                       /* Update the environment directory chain: */
    if (chaincnt == 1)         /* special case: record old dir */

    {
        if (m_putenv(chnevar1, cwdbuf))
            error("Error setting environment variable");
        return 0;
    }

    for (i = 1; ; i++)

    {               /* get name of current dirname variable */

        strcpy(chnevar1, CHAIN_BASE);
        strcat(chnevar1, itoa(i, itoabuf, 10));

        strcpy(chnevar2, CHAIN_BASE);
        strcat(chnevar2, itoa(i + 1, itoabuf, 10));

        if (!(chndname = m_getenv(chnevar2)))

            break;   /* found end of saved chain */

                /* copy value of next higher to current */
        strcpy(chndname_save, chndname);   /* m_putenv() bashes it */
        strcpy(chnevar1, CHAIN_BASE);
        strcat(chnevar1, itoa(i, itoabuf, 10));
        if (m_putenv(chnevar1, chndname_save))

            error("Error setting environment variable");
    }
    return 0;
}