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

时间:2015-11-19 04:22:12

标签: c arrays scanf

我正在尝试使用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

2 个答案:

答案 0 :(得分:4)

这是一个错误:

bw.write(message);

bw.write(new Timestamp(new java.util.Date().getTime()).toString()); 是一个未初始化的变量,因此它不能用于数组维度(或其他任何东西)。

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

int process_count, p_id[process_count],

答案 1 :(得分:2)

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

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

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