Home > front end >  Parsing a csv file into two string arrays using C Programming
Parsing a csv file into two string arrays using C Programming

Time:11-16

Hello I am trying to read data from a CSV file, parsing it by "," and trying to store into two different arrays user and password. However, I am not able to store token data into string arrays. I am not sure how to fix it :(.

Here is my code,

#include<stdio.h>

int main(){
        
    FILE *fptr;
    char row[100];
    char usr[100][100];
    char pwd[100][100];

    fptr = fopen("users.csv", "r");
    int i = 0;
    int j = 0;

    while( fgets(row, 100, fptr) ){
        char *token;
        token = strtok(row, ",");
        strcpy(usr[i], token);

        while(token != NULL){
            printf("%s", token);
            strcpy(pwd[i], token);

            printf("\n");
        }
        i  ;
        printf("\n");
    }

    for(int k = 0; i < 100; i  ){
        if(usr[k] == NULL || pwd[k] == NULL)
            break;
        printf("%s", usr[k]);
        printf("%s", pwd[k]);
    }
}

I am getting the following output: enter image description here

CodePudding user response:

Your problem is the second while loop inside the first one. That has no terminating condition because of which it keeps going into an infinite loop.

Like Craig Estey mentioned in the comments, you could keep the while loop and just add another strtok(NULL, row) to make sure that you read the entire line instead of just reading the first token (in this case, the string before the first comma in a line). Or if you are sure that there is only going to be 2 columns in a row, then you could just call the strtok twice to read the two tokens and assign them to your arrays.

Also, your final loop to print is wrong. Character Arrays in C are not initialized with NULL by default so checking for NULL won't work unless you loop through first and set everything to NULL before starting the file processing. Instead, keep track of the number of lines you read from the file and then use that as the loop counter to print your variables.

Essentially, something like this will work:

FILE *fptr;
char row[100];
char usr[100][100];
char pwd[100][100];
fptr = fopen("users.csv", "r");

int lineCounter = 0;
while( fgets(row, 100, fptr) ) {
    char *token;
    token = strtok(row, ",");
    strcpy(usr[lineCounter], token);
    token = strtok(NULL, ",");
    while(token != NULL) { // What this does is if your line is malformed like "ABC,123,12334,12233,Abc" then usr[i] would be ABC and pwd[i] would be Abc. It will only consider the first and last tokens. 
        strcpy(pwd[lineCounter], token);
        token = strtok(NULL, ",");
    }
    lineCounter  ;
}

for(int k=0; k < lineCounter; k  ) {
    printf("User: %s  -- Password: %s\n", usr[i], pwd[i]);
}
  • Related