【发布时间】:2015-11-19 04:22:12
【问题描述】:
我正在尝试使用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
【问题讨论】:
-
如果先将数组清零会怎样?
-
你需要设置
process_count的值在你使用它来指定数组的大小。您的数组很可能都是零长度(尽管这不可靠,因为此时process_count未初始化)。