Kshitiz Kshitiz - 2 months ago 13
C Question

C - Reading CSV file in char array

I have a very little experience in C programming, particularly File Handling. I am developing a project in which I'm supposed to create a Sign Up/Log In system. I have a .csv file in which the data are separated by ,
What I am trying to do is reading the first and second column into two char arrays respectively.

char userLogin[100];
char userPassword[100];
FILE *file3 = fopen("C:\\Users\\Kshitiz\\Desktop\\BAAS\\signup_db.csv","r");
if(file3 != NULL){
while(!feof(file3)){
fscanf(file3,"%[^,],%s",userLogin,userPassword);
puts(userLogin);
puts(userPassword);
}

}


fclose(file3);


Content of signup_db.csv:

Username,Password
SBI063DDN,Qazwsx1234
ICICIDDN456,WSXEDC1234r


Expected Output:

Username
Password

SBI063DDN
Qazwsx1234

ICICIDDN456
WSXEDC1234r


Output which I'm getting:

Username
Password

SBI063DDN
Qazwsx1234

ICICIDDN456
WSXEDC1234r


WSXEDC1234r


Can anyone please help me how can I resolve this issue? Thank you!

Mat Mat
Answer

The 'fscanf()' function returns the number of items of the argument list successfully filled. So instead try this:

while(fscanf(file3,"%[^,],%s",userLogin,userPassword) == 2)
{
  puts(userLogin);
  puts(userPassword);
}

The problem you mentioned is probably because of a new line character at the end of your file. When you read the last line, you have not yet reached the end of file. The above code solves this issue.