So I have a .txt file that has records looking like this:
1234567, John, Doe
and I have arrays in my C code where I want to read these values and insert them into:
int id[36] = {0};
char first_name[36];
char last_name[36];
So they idea is that,for example, 1234567 is at index 0 of id, John is at index 0 of first_name, and doe is at index 0 of last_name. And I want to do this with 36 similar lines.
I've investigated FILE IO but I haven't found anything pertaining to this. What's the best way of doing it? Thanks for any responses.
Make a loop that reads the content of your file using fscanf
. Check the return value to be 3
indicating that all three items were read:
// id is OK as os
int id[36] = {0};
// make first_name and last_name arrays of arrays
char first_name[36][36];
char last_name[36][36];
int i = 0;
while (fscanf(fd, "%d, %35[^,], %35s", &id[i], first_name[i], last_name[i]) == 3) {
i++;
if (i == 36) {
break;
}
}
The format string of fscanf
specifies the first argument is an int
followed by a comma and whitespace, then a sequence of 35 non-commas, a comma again, and up to 35 characters for the last name.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With