C从文本文件中读取值
问题描述:
我正在编写一个c程序来模拟FCFS调度算法。它将接受命令行参数作为文件并计算每个进程的周转时间和等待时间。但是它不能将文本文件中的值成功读入变量。 下面是代码C从文本文件中读取值
#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);
}
这里是输入文件
,输出是
感谢任何帮助和建议。
答
正如指出为ALK,你正在做一些错误:
- 在您的结构声明您已声明
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);
+0
感谢您的建议。问题解决了。 – harry
一)'焦炭name'商店***只有一个***字符,这就是它。 b。)认真对待编译器的警告。 – alk
用所有警告和调试信息编译('gcc -Wall -Wextra -g')然后**使用调试器**'gdb' –
感谢您的建议。问题解决了。 – harry