我正在编写一个c程序来模拟FCFS调度算法。它将接受命令行参数作为文件,并计算每个进程的周转时间和等待时间。但是,它无法成功地将文本文件中的值读入变量。 这是代码
#include <stdio.h>
#define N 50
int main(int argc, char** argv)
{
int i = 0;
char line[20];
int n=0;
typedef struct
{
char name; //process name
int at; //arrive time
int pt; //process time
int ft; //finish time
int rt; //round time
int wt; //wait time
} Process;
Process pcs[N];
FILE* file = fopen( argv[1], "r");
while (fgets(line,sizeof(line),file) != NULL)
{
sscanf(line, "%s %d %d", pcs[i].name, pcs[i].at, pcs[i].pt);
line[strlen(line)-1] = '\0';
printf("%s %d %d\n",pcs[i].name, pcs[i].at, pcs[i].pt);
i++;
}
fclose(file);
pcs[0].ft=pcs[0].at+pcs[0].pt;
pcs[0].rt=pcs[0].ft-pcs[0].at;
pcs[0].wt=0;
for (n;n<4;n++)
{
if (pcs[n].at<pcs[n-1].ft)
{
pcs[n].ft=pcs[n-1].ft+pcs[n].pt;
pcs[n].rt=pcs[n].ft-pcs[n].at;
pcs[n].wt=pcs[n-1].ft-pcs[n].at;
}
else
{
pcs[n].ft=pcs[n].at+pcs[n].pt;
pcs[n].rt=pcs[n].ft-pcs[n].at;
pcs[n].wt=pcs[n-1].ft-pcs[n].at;
}
}
int x = 0;
for (x;x<n;x++)
{
printf("process name: %s", pcs[x].name);
printf("Turnaround Time: %d", pcs[x].rt);
printf("Wait Time: %d\n", pcs[x].wt);
}
return(0);
}
这是输入文件
输出
感谢您提供任何帮助和建议。
答案 0 :(得分:2)
正如我所指出的那样,你犯了一些错误:
name
声明为单个字符,但在您的文件中读取代码(包含fgets
的循环),您将通过%s
字符串,所以最好将声明更改为char name[SIZE]
而不是char name
。 Bdw你应该阅读编译器警告并尝试理解它,因为那是造成问题的原因。sscanf
及其变体中传递变量的地址,因此将第26行更改为:
sscanf(line, "%s %d %d", pcs[i].name, &pcs[i].at, &pcs[i].pt);