ping获取延时的问题
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define CMD_LEN 1024
#define PING_DESTINATION "192.168.1.1"
#define NET_DELAY_TIME_KEY "time="
#define PING_NUM 1
void count_average_time(float delay[],int ping_num,float *delay_time)
{
int i = 0;
float sum= 0;
for (;i < ping_num; i++)
{
sum = sum + delay[i];
}
*delay_time = sum / ping_num ;
}
int get_delay_time(float *average_time)
{
char buf[64] = {0};
int net_level = 0;
char cmd[CMD_LEN] = {0};
FILE *pf = NULL;
char *delay_time = NULL;
float delay[PING_NUM] = {0};
int i = 0;
int j = 0;
snprintf(cmd,CMD_LEN,"ping %s",PING_DESTINATION);
pf = popen(cmd,"r");
if (pf == NULL)
{
return 1;
}
while((fgets(buf,64,pf) != NULL) && (j <= PING_NUM))
{
printf("%s",buf);
if ((delay_time = strstr(buf,NET_DELAY_TIME_KEY)) != NULL)
{
delay_time = delay_time + strlen(NET_DELAY_TIME_KEY);
delay[i++] = atof(delay_time);
printf("%f\n",delay[i-1]);
}
j++;
}
pclose(pf);
count_average_time(delay,PING_NUM,average_time);
return 0;
}
int main()
{
float average_time = 0;
get_delay_time(&average_time);
printf("%f\n",average_time);
return 0;
}
[解决办法]
char *fgets(char *s, int n, FILE *stream)
fgets reads at most the next n-1 characters into the array s, stopping if a newline is encountered; the newline is included in the array, which is terminated by '\0'. fgets returns s, or NULL if end of file or error occurs.
是否文件系统对 newline 的定义不同