zoukankan      html  css  js  c++  java
  • UNIX环境高级编程——环境变量表读取/添加/修改/删除

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    int main()
    {
    	char* pValue;
    	pValue = getenv("HOME"); // 起始目录(主目录)
    	 printf("$HOME = %s
    ", pValue);
    	// 在主目录下建立a.txt文件
    	char szFilePath[100];
    	strcpy(szFilePath, pValue);
    	strcat(szFilePath, "/a.txt");
    	FILE* f = fopen(szFilePath, "w+");//w+ 打开可读写文件,若文件存在则文件长度清为零,即该文件内容会消失。若文件不存在则建立该文件。
    	if(f == NULL)
    	   perror("fopen");
    	fclose(f);
    	// 打印当前工作绝对路径
    	char* pCurPath;
    	pCurPath = getenv("PWD");
    	printf("$PWD=%s
    ", pCurPath);
    	// 打印登录名
    	char* pLogName;
    	pLogName = getenv("LOGNAME");
    	printf("$LOGNAME=%s
    ", pLogName);
    	// 插入新的环境变量
    	int ret;
    	ret = putenv("HC=huangcheng");
    	if (ret != 0)
    	{
    		printf("putenv  Error!" );
    		exit(-1);
    	}
    	pValue = getenv("HC");
    	printf("echo $HC=%s
    ", pValue);
    	// 改变环境变量的值
    	ret = setenv("HC", "ctthuangcheng", 1);
    	if (ret != 0)
    	{
    		printf("setenv  Error!" );
    		exit(-1);
    	}
    	pValue = getenv("HC");
    	printf("echo $HC=%s
    ", pValue);
    	// 删除环境变量
    	ret = unsetenv("HC");
    	if (ret != 0)
    	{
    		printf("unsetenv  Error!" );
    		exit(-1);
    	}
    	pValue = getenv("HC");
    	printf("echo $HC=%s
    ", pValue);
    	
    	return 0;
    }
    

    运行结果:

    huangcheng@ubuntu:~$ ./a.out
    $HOME = /home/huangcheng
    $PWD=/home/huangcheng
    $LOGNAME=huangcheng
    echo $HC=huangcheng
    echo $HC=ctthuangcheng
    echo $HC=(null)
    


  • 相关阅读:
    Linux下用命令格式化U盘
    ABAP
    [Java 并发] Java并发编程实践 思维导图
    html和css实现一级菜单和二级菜单学习笔记
    小贝_mysql建表以及列属性
    Android.mk具体解释
    Maven之——坐标和依赖(上)
    让 Nginx 支持 WAF 防护功能web防火墙
    EZHTTP首页、文档和下载
    http://www.sshguard.net/
  • 原文地址:https://www.cnblogs.com/hehehaha/p/6332475.html
Copyright © 2011-2022 走看看