I need to read from a file from using C.
#include <stdio.h>
struct record{
char name[2];
int arrival_time;
int job_length;
int job_priority;
};
const int MAX = 40;
main(){
struct record jobs[MAX];
FILE *f;
fopen("data.dat","rb");
int count =0;
while(fscanf(f, "%c%c %d %d %d", &jobs[count].name, &jobs[count].arrival_time, &jobs[count].job_length, &jobs[count].job_priority) != EOF){
count++;
}
int i;
for(i =0;i<count;i++){
printf("%c%c %d %d %d", &jobs[count].name, &jobs[count].arrival_time, &jobs[count].job_length, &jobs[count].job_priority);
}
}
The data file’s format is the following:
A1 3 3 3
B1 4 4 4
C1 5 5 5
…
First one is char[2] and the other three int. I can’t get the code right to read in until the end of file.
Anyone come across this before?
Updated Code.
There are a couple of modifications needed – most notably, you need to reference the
jobsarray of structures:I make sure the loop doesn’t overflow the array. I print the data out (it is the most basic form of checking that you’ve read what you expected). The most subtle issue is the use of
jobs[i].name[0]; this is necessary to read and print a single character. There’s no guarantee that there is any particular value injobs[i].name[1]; in particular, it is quite probably not an NUL'\0', and so the name is not null terminated. It seems a bit odd using a single character name; you might want to have a longer string in the structure:The
&is now not needed. The%.39snotation is is used to read a length-limited string up to the first space. Note that the size in the string is one less than the size of the array. It can often be simplest simply to create the format string withsprintf()to get the size right.The code does not error check the
fopen()statement.I discussed names longer than one character…
If you need to read “A1”, you need the
namemember to be bigger so that you can null terminate the string, and you need to use%srather than%cto read the value, and you need to lose the&and subscript, and you need to protect your code from buffer overflow (because where you expect ‘A1’, someone will inevitably enter ‘A1B2C3D4D5F6G7H8I9J10K11L12M13’ and wreak havoc on your code if you do not protect against the buffer overflow. Incidentally, the change in the test of the result offscanf()(from== EOFto!= 4was also a protection against malformed input; you can get zero successful conversions without reading any characters, in general – though your%cwould eat one character per iteration).