Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: Reading file from txt file and inserting into arrays. comma as a separator

Tags:

arrays

c

file-io

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.

like image 417
Giancarlo Manuel Guerra Salvá Avatar asked Mar 17 '23 06:03

Giancarlo Manuel Guerra Salvá


1 Answers

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.

like image 81
Sergey Kalinichenko Avatar answered Apr 27 '23 18:04

Sergey Kalinichenko