写文件 —— 将内容按照指定格式写入配置文件(fprintf()函数-》》本机的监听地址列表中port值)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_42167759/article/details/84337852

例如 —— 文件中的配置内容格式如下:

listen的文件的内容为

listen  33;

listen   24;

参数说明

编辑

int fprintf (FILE* stream, const char*format, [argument])

FILE*stream:文件指针

const char* format:输出格式

[argument]:附加参数列表

函数说明

编辑

fprintf( )会根据参数format 字符串来转换并格式化数据, 然后将结果输出到参数stream 指定的文件中, 直到出现字符串结束('\0')为止。


运行结果显示:

[root@J01051386 mapproxy]# cat listen 
listen 11223;
listen 25;
listen 1224;
listen 8080;

代码部分:

#include <stdio.h>
#include <string.h>
int main()
{
	int bl = 0;
	char *pcpos = NULL;
	FILE *fp = NULL; 
	FILE *pf = NULL;
	char szListen[2048] = {0};

	pf = popen("sudo netstat -nl | grep tcp  | awk '{print $4}' | awk '{split($0,a,\":\");print a[2]a[4]}'", "r");
	if(NULL == pf)
	{
		return 1;
	}

	if((fp = fopen("/usr/local/nginx/conf/mapproxy/listen", "w")) == NULL)
	{
		printf("Cannot open output file.\n");
		return 1;
	}

	while(NULL != fgets(szListen, sizeof(szListen), pf))
	{	
		szListen[strlen(szListen) - 1] = '\0';
		fprintf(fp, "listen %s;\n", szListen);
	}

	fclose(fp);
	fclose(pf);
	return 0; 
}

相关问题:

[root@localhost netsec+]# sudo netstat -nl | grep tcp    (匹配tcp与tcp6的数据)

tcp        0      0 0.0.0.0:11223           0.0.0.0:*               LISTEN     
tcp        0      0 0.0.0.0:25              0.0.0.0:*               LISTEN     
tcp6       0      0 :::1224                 :::*                    LISTEN     
tcp6       0      0 :::8080                 :::*                    LISTEN

[root@localhost netsec+]# sudo netstat -nl | grep -w tcp    (匹配tcp数据)

tcp        0      0 0.0.0.0:11223           0.0.0.0:*               LISTEN     
tcp        0      0 0.0.0.0:25              0.0.0.0:*               LISTEN     
tcp6       0      0 :::1224                 :::*                    LISTEN     
tcp6       0      0 :::8080                 :::*                    LISTEN

猜你喜欢

转载自blog.csdn.net/weixin_42167759/article/details/84337852