Reputation: 45
I am trying to use fscanf
to read a file and store its contents in arrays. Each line contains four integer values, which need to be placed in four different arrays. My code reads each line, but stores the final integer value of each line in all four arrays.
I've tried using fgets()
, which seemed to cause even more problems. Changing the format in the fscanf()
call hasn't helped either.
Why is it skipping the first three values of each line?
code:
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);
input:
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
output:
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
Upvotes: 1
Views: 113
Reputation: 141628
This is an error:
int process_count, p_id[process_count],
process_count
is an uninitialized variable so it cannot be used for an array dimension (or anything else really).
To fix this you could change the code to:
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];
Upvotes: 4
Reputation: 14046
You have undefined behaviour in your program.
int process_count, p_id[process_count], io_burst[process_count], cpu_burst[process_count];
...
process_count = atoi(argv[2]);
That code is using process_count
before it has been intialised.
Upvotes: 2