Linux ShellコマンドのC言語実装


Linux ShellコマンドのC言語実装に関するいくつかの関数と例をここに記録します.
/*****************************************************
 * Author: Robin
 * Mail: [email protected]
 * Description:
 * Linux shell    c    
 ******************************************************
 *         ————getenv()
 * NAME
 *        getenv - get an environment variabl
 *
 * SYNOPSIS
 *        #include 
 *
 *        char *getenv(const char *name);
 ******************************************************
 *          ————getcwd, getwd, get_current_dir_name
 *NAME
 *       getcwd, getwd, get_current_dir_name - Get current working directory

 *SYNOPSIS
 *      #include 
 *      char *getcwd(char *buf, size_t size);
 *      char *getwd(char *buf);
 *      char *get_current_dir_name(void);
 ******************************************************/
#include 
#include 
#include 
#include 
#ifndef MAXPATHLEN
#define MAXPATHLEN 1024
#endif

char *getcwd (char *buf, size_t len)
{
    char ourbuf[MAXPATHLEN];
    char *result;

    result = (char*)getwd (ourbuf);
    if (result) {
        if (strlen (ourbuf) >= len) {
            errno = ERANGE;
            return 0;
        }
        if (!buf) {
            buf = (char*)malloc(len);
            if (!buf) {
                errno = ENOMEM;
                return 0;
            }
        }
        strcpy (buf, ourbuf);
    }
    return buf;
}

int main(int argc, char** argv, char** envp){
    char *home;
    char *dir;
    char buf[1024];

    puts((char*)getenv("PATH"));

    home = (char*)getenv("HOME");
    puts(home);

    dir = (char*)getcwd(buf, sizeof(buf));
    puts(dir);

    puts((char*)get_current_dir_name());
    return 0;
}