Linux下C语言使用popen获取一个文件的内容小实例

#include 
#include 
#include 
#include 

void printpwd(struct passwd *pwd)
{
	printf("name:%s\n", pwd->pw_name);
	printf("passwd:%s\n", pwd->pw_passwd);
	printf("uid:%u\n", pwd->pw_uid);
	printf("gid:%u\n", pwd->pw_gid);
	printf("gecos:%s\n", pwd->pw_gecos);
	printf("dir:%s\n", pwd->pw_dir);
	printf("shell:%s\n", pwd->pw_shell);
}
int main(void)
{
	FILE *pf;
	char filepath[128] = {0};
	char readcmd[128] = {0};
	struct passwd *pwd;
	char buff[24] = {0};

	/*获取当前用户的信息*/
	pwd = getpwuid(getuid());
	printpwd(pwd);//打印

	/*根据用户名组建文件路径*/
	snprintf(filepath, 128, "/home/%s/test.conf", pwd->pw_name);

	/*组建shell命令*/
	snprintf(readcmd, 128, "cat %s", filepath);

	/*判断文件是否存在,如果不存在则创建,并赋予初始值为hello world*/
	if(access(filepath, F_OK) == -1)
	{
		popen("echo 'hello world' > ~/test.conf", "r");
	}

	/*通过popen运行shell命令,并通过返回的文件描述符读取文件中的内容*/
	if((pf = popen(readcmd, "r")) != NULL)
	{
		if(fgets(buff, 24, pf) != NULL)
			printf("content in %s is:%s", filepath, buff);
		pclose(pf);//这里不能用fclose()!
		pf = NULL;
	}


	return 0;
}




编译运行效果:

你可能感兴趣的:(Linux)