-2

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!

Kshitiz
  • 3,431
  • 4
  • 14
  • 22

2 Answers2

0

In my case I have the expected results, but I don't know if there is a difference with the compiler or if my csv file is different (I've tried to recreate it). Here is another way to parse the file, check if you have the expected results:

#include <stdio.h>
#include <string.h>

#define LINE_LENGTH 1000

int main(void) {
  char userLogin[100];
  char userPassword[100];

  char line[LINE_LENGTH];
  char *delimiter = ",";
  char *token;

  FILE *file3 = fopen("signup_db.csv", "r");

  while(fgets(line, LINE_LENGTH, file3) != NULL) {
    token = strtok(line, delimiter);
    printf("%s\n", token);
    token = strtok(NULL, delimiter);
    printf("%s\n", token);
  }

  fclose(file3);
}
Stavros Zavrakas
  • 3,045
  • 1
  • 17
  • 30
0

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.

Mat
  • 116
  • 5