fscanf() 只读取每行的最后一个整数

fscanf() only reads last integer per line

我正在尝试使用 fscanf 读取文件并将其内容存储在数组中。每行包含四个整数值,需要将它们放在四个不同的数组中。我的代码读取每一行,但将每一行的最终整数值存储在所有四个数组中。

我试过使用 fgets(),这似乎导致了更多问题。更改 fscanf() 调用中的格式也无济于事。

为什么它会跳过每行的前三个值?

代码:

FILE *file;
int process_count, p_id[process_count], io_burst[process_count], priority[process_count], cpu_burst[process_count];

file = fopen(argv[1], "r");
if (!file) { error("File open failed"); }

process_count = atoi(argv[2]);

for (int i = 0; i < process_count; i++)
{
    if (fscanf(file, "%i %i %i %i", &p_id[i], &cpu_burst[i], &io_burst[i], &priority[i]) < 4)
    {
        error("File read failed");
    }

    printf("p_id: %i\n", p_id[i]);
    printf("cpu_burst: %i\n", cpu_burst[i]);
    printf("io_burst: %i\n", io_burst[i]);
    printf("priority: %i\n\n", priority[i]);
}

fclose(file);

输入:

0           10           4           2
1            8           2           1
2           12           0           5
3            2           4           4
4            8           3           0
5            6           4           2
6            4           0           5
7           16           7           5
8           14           0           1
9            2          10           1

输出:

p_id: 2
cpu_burst: 2
io_burst: 2
priority: 2

p_id: 1
cpu_burst: 1
io_burst: 1
priority: 1

p_id: 5
cpu_burst: 5
io_burst: 5
priority: 5

p_id: 4
cpu_burst: 4
io_burst: 4
priority: 4

p_id: 0
cpu_burst: 0
io_burst: 0
priority: 0

p_id: 2
cpu_burst: 2
io_burst: 2
priority: 2

p_id: 5
cpu_burst: 5
io_burst: 5
priority: 5

p_id: 5
cpu_burst: 5
io_burst: 5
priority: 5

p_id: 1
cpu_burst: 1
io_burst: 1
priority: 1

p_id: 1
cpu_burst: 1
io_burst: 1
priority: 1

您的程序中有未定义的行为。

int process_count, p_id[process_count], io_burst[process_count], cpu_burst[process_count];
...
process_count = atoi(argv[2]);

该代码在初始化之前正在使用 process_count

这是一个错误:

int process_count, p_id[process_count],

process_count 是一个未初始化的变量,因此它不能用于数组维度(或其他任何东西)。

要解决此问题,您可以将代码更改为:

int process_count = atoi(argv[2]);

if ( process_count < 1 )
    exit(EXIT_FAILURE);    // or similar

int p_id[process_count], io_burst[process_count], priority[process_count], cpu_burst[process_count];