/proc/net/dev 最后一行读2次

网络2倍字节量和网速,百思不得其解。

void netdev(SamplePlugin *sample)
{
  FILE *fp;
  char s[150], itf[10];
  long long r1, r2, r3, r4, r5, r6, r7, r8, t1, t2, t3, t4, t5, t6, t7, t8;
  int i=0;
  sample->rb = 0;
  sample->tb = 0;
  fp = fopen("/proc/net/dev", "r");
  while (!feof(fp)) {
    fgets(s, sizeof(s), fp);
    if (i > 1) {
      sscanf(s, "%s%Ld%Ld%Ld%Ld%Ld%Ld%Ld%Ld%Ld%Ld%Ld%Ld%Ld%Ld%Ld%Ld", itf, &r1, &r2, &r3, &r4, &r5, &r6, &r7, &r8, &t1, &t2, &t3, &t4, &t5, &t6, &t7, &t8);      
      g_message("%d\t%s", i, s);
      sample->rb += r1;
      sample->tb += t1;
    }
    i++;
  }
  fclose(fp); 
}

/proc/net/dev 最后一行读2次_第1张图片

 fgets与feof 判断文件结尾总结_fgets读到文件末尾_Lawrence_121的博客-CSDN博客

void netdev(SamplePlugin *sample)
{
  FILE *fp;
  char s[150], itf[10];
  long long r1, r2, r3, r4, r5, r6, r7, r8, t1, t2, t3, t4, t5, t6, t7, t8;
  int i=0;
  sample->rb = 0;
  sample->tb = 0;
  fp = fopen("/proc/net/dev", "r");
  while (1) {        
    fgets(s, sizeof(s), fp);
    if (feof(fp)) {
      fclose(fp);
      break;
    }
    if (i > 1) {
      sscanf(s, "%s%Ld%Ld%Ld%Ld%Ld%Ld%Ld%Ld%Ld%Ld%Ld%Ld%Ld%Ld%Ld%Ld", itf, &r1, &r2, &r3, &r4, &r5, &r6, &r7, &r8, &t1, &t2, &t3, &t4, &t5, &t6, &t7, &t8);      
      //g_message("%d\t%s", i, s);
      sample->rb += r1;
      sample->tb += t1;
    }
    i++;
  }
}

 

你可能感兴趣的:(C++,c++)