[英]C read values from text file
我正在編寫 ac 程序來模擬 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);
}
這是輸入文件
輸出是
感謝您的任何幫助和建議。
正如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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.