阅读从文本文件的int到C中的数组 [英] Reading an int from a text file into an array in C

查看:65
本文介绍了阅读从文本文件的int到C中的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有此格式的文本文件:

I've got a text file formatted like this:

100 0 10 1
101 6 10 1
102 8 4 1
103 12 20 1
104 19 15 1
105 30 5 1
106 35 10 1

我需要把这些数字放入数组PID [],到达[],阵阵[]和优先级[],分别为。 C是不是我的最强的语言,所以我有一些麻烦这样做。

I need to put these numbers into the arrays pID[], arrival[], bursts[], and priority[], respectively. C is not my strongest language, so I'm having some trouble doing this.

下面是我目前的code:

Here's my current code:

void readFile(int n, int pID[], int arrival[], int bursts[], int priority[]){
FILE *file;
int i = 0;
file = fopen("Process.txt", "r");

//File format is pID, arrival, bursts, and priority
if (file){
    while (!feof(file)){
        pID[i] = fscanf(file, "%d ", &i);
        arrival[i] = fscanf(file, "%d ", &i);
        bursts[i] = fscanf(file, "%d ", &i);
        priority[i] = fscanf(file, "%d ", &i);
    }
    fclose(file);
}

感谢您的帮助!

推荐答案

您正在使用的feof 的fscanf 中错误的方法。我建议您一次读取文件中的一行,检查被读取,然后从缓存器扫描值,也检查数组索引仍然是确定和字段的正确数量进行扫描。

You are using feof and fscanf in the wrong way. I suggest you read one line from file at a time, checking it was read, and then scanning the values from the buffer, also checking that the array index is still ok, and the correct number of fields were scanned.

void readFile(int n, int pID[], int arrival[], int bursts[], int priority[]) {
    FILE *file;
    int i = 0;
    char buffer[100];
    file = fopen("Process.txt", "r");
    if (file){
        while (i < n && fgets(buffer, sizeof buffer, file) != NULL) {
            if(sscanf(buffer, "%d%d%d%d", &pID[i], &arrival[i], &bursts[i], &priority[i]) != 4) {
                exit(1);                // or recovery strategy
            }
            i++;
        }
        fclose(file);
    }
}

这篇关于阅读从文本文件的int到C中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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