UNIX环境高级编程——环境变量表读取/添加/修改/删除

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
	char* pValue;
	pValue = getenv("HOME"); // 起始目录(主目录)
	 printf("$HOME = %s\n", 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\n", pCurPath);
	// 打印登录名
	char* pLogName;
	pLogName = getenv("LOGNAME");
	printf("$LOGNAME=%s\n", pLogName);
	// 插入新的环境变量
	int ret;
	ret = putenv("HC=huangcheng");
	if (ret != 0)
	{
		printf("putenv  Error!" );
		exit(-1);
	}
	pValue = getenv("HC");
	printf("echo $HC=%s\n", pValue);
	// 改变环境变量的值
	ret = setenv("HC", "ctthuangcheng", 1);
	if (ret != 0)
	{
		printf("setenv  Error!" );
		exit(-1);
	}
	pValue = getenv("HC");
	printf("echo $HC=%s\n", pValue);
	// 删除环境变量
	ret = unsetenv("HC");
	if (ret != 0)
	{
		printf("unsetenv  Error!" );
		exit(-1);
	}
	pValue = getenv("HC");
	printf("echo $HC=%s\n", pValue);
	
	return 0;
}

运行结果:

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


转载于:https://www.cnblogs.com/hehehaha/p/6332475.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值