解析文本文件的简单方法? [英] easy way to parse a text file?

查看:227
本文介绍了解析文本文件的简单方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个负载均衡器(一个非常简单的负载均衡器).它查看用户闲置了多长时间,以及系统上的负载以确定进程是否可以运行,并以循环方式遍历进程.

I'm making a load balancer (a very simple one). It looks at how long the user has been idle, and the load on the system to determine if a process can run, and it goes through processes in a round-robin fashion.

控制过程所需的所有数据都存储在一个文本文件中. 该文件可能如下所示:

All of the data needed to control the processes are stored in a text file. The file might look like this:

 PID=4390 IDLE=0.000000 BUSY=2.000000 USER=2.000000
 PID=4397 IDLE=3.000000 BUSY=1.500000 USER=4.000000
 PID=4405 IDLE=0.000000 BUSY=2.000000 USER=2.000000
 PID=4412 IDLE=0.000000 BUSY=2.000000 USER=2.000000
 PID=4420 IDLE=3.000000 BUSY=1.500000 USER=4.000000

这是大学的作业,但是解析文本文件不应该占很大一部分,这意味着我可以使用对我来说最快的方法.

This is a university assignment, however parsing the text file isn't supposed to be a big part of it, which means I can use whatever way is the quickest for me to implement.

此文件中的条目将在进程完成时添加或删除,或者在控制下添加.

Entries in this file will be added and removed as processes finish or are added under control.

有关如何解析此内容的任何想法?

Any ideas on how to parse this?

谢谢.

推荐答案

这是一个代码,它将解析您的文件,并考虑到您的文件可能不可用(即fopen可能失败)的事实,或在阅读时被写入(即fscanf可能会失败).请注意,您可能不想使用无限循环(这比要复制粘贴到您的项目中的实际代码更多的伪代码,我没有尝试运行它).还要注意,考虑到那里的睡眠时间,它可能会很慢:您可能想使用更高级的方法,这更像是一种hack.

Here is a code that will parse your file, and also account for the fact that your file might be unavailable (that is, fopen might fail), or being written while you read it (that is, fscanf might fail). Note that infinite loop, which you might not want to use (that's more pseudo-code than actual code to be copy-pasted in your project, I didn't try to run it). Note also that it might be quite slow given the duration of the sleep there: you might want to use a more advanced approach, that's more sort of a hack.

int pid;
float idle, busy, user;

FILE* fid;
fpos_t pos;
int pos_init = 0;

while (1)
{
  // try to open the file
  if ((fid = fopen("myfile.txt","rw+")) == NULL)
  {
     sleep(1); // sleep for a little while, and try again
     continue; 
  }

  // reset position in file (if initialized)
  if (pos_init)
     fsetpos (pFile,&pos);

  // read as many line as you can
  while (!feof(fid))
  {
     if (fscanf(fid,"PID=%d IDLE=%f BUSY=%f USER=%f",&pid, &idle, &busy, &user))
     {
        // found a line that does match this pattern: try again later, the file might be currently written
        break;
     }

     // add here your code processing data         

     fgetpos (pFile,&pos); // remember current position
     pos_init = 1; // position has been initialized
  }

  fclose(fid);
}

这篇关于解析文本文件的简单方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆