输入文件中的作业计划

Job scheduling from input file

本文关键字:作业 计划 文件 输入      更新时间:2023-10-16

我正在为我的操作系统类开发一个模拟的进程调度程序,并且很难找到从要处理的文件中提取数据的最佳方法。输入文件如下所示:

5
1 3 10
2 4 15
3 6 8
4 7 3
5 9 12

其中,第一个数字是进程的数量,每行包含:(1)作业编号、(2)到达时间和(3)CPU循环时间。

我必须使用FCFS、SJF、SRT和Round Robin来处理作业。

这是我到目前为止所做的工作的一部分,但我很难弄清楚如何以更容易处理的方式从文件中获取数据(或者,我有点卡住了)。

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct job
{
 int id, arrTime, cpuTime;
};
int main()
{
 fstream input;
 job job1, job2, job3, job4, job5, job6, job7,job8, job9, job10;
 char n, *id, *at, *cpu; 
 int proc;  
 input.open("input.txt");
 input.get(n);
 proc = n;


 return 0;
}

我正在考虑从给定的10个作业中提取每一点信息,并将其放入10个作业类对象中。此外,有没有一种好的方法可以实现代码,从而允许任何数量的作业?

使用类似std::vector的容器来存储作业。好的I/O既难又乏味:

例如:

// container to hold jobs
// remember to #include <vector>
std::vector<job> myJobs;

然后在中阅读

// read in number of jobs:
// going to need #include <fstream> and <sstream>
ifstream input("input.txt");
if (!input)
{
   std::cerr << "Failed to open input file! Cannot continuen";
   exit(1);
}
int numJobs = 0;
if (input >> numJobs)
{
   myJobs.reserve(numJobs);
}
else
{
   std::cerr << "Failed to read number of jobs. Cannot continuen";
   exit(1);
}
std::string nextline;
for (int i=0;i<numJobs && std::getline(input >> std::ws, nextLine); ++i)
{
   std::stringstream inStream(nextLine);
   job nextJob;
   nextLine >> nextJob.id >> nextJob.arrTime >> nextJob.cpuTime;
   if (!inStream)
   {
      std::cerr << "Error reading next jobn";
      break;
   }
   myJobs.push_back(nextJob);
}
input.close();
std::cout << "Was supposed to read in " << numJobs << " jobs. Successfully read in " << myJobs.size() << " jobs.";

然后对容器做你想做的事:

// Now you can do what you want with them
// Let's sort them from smallest cpuTime to largest!
// remember to #include<algorithm>
std::sort(std::begin(myJobs), std::end(myJobs), [](const job& lhs, const job& rhs){return lhs.cputime < rhs.cputime;});
cout << "Jobs sorted by cputime: n";
for (auto&& j : myJobs)
{
   cout << j.id << " " << j.arrTime << " " << j.cpuTime << std::endl;
}

编辑我在这篇文章中使用了一些C++11,所以如果你只使用C++98/03 ,它将不会编译