Question

I would like to read from a .csv file line by line and then check if the first word of my line matches string_1. If it matches, then I would also like to check if the second word matches string_2. My .csv file contains three fields, namely user, password and type. Here is my code so far:

void verify ( char *user, char *password ) {

    FILE *data;
    char verifyUser[50];

    data = fopen( "password.csv", "r+" );
    while ( fgets(verifyUser, 50, data ) != NULL) {

        char *ptr;
        ptr = strtok(verifyUser, ", ");

        /***What do I do here?***/
    }

    fclose(data);
}

In this case, user and password are string_1 and string_2 respectively. Any tips? Can I use strtok to split my line into three substrings, and then perform strcmp on them? If so, how do I do that?

Was it helpful?

Solution

How about something along these lines:

ptr = strtok(verifyUser, ", ");
if (!ptr || strcmp(ptr, user))
    continue;

/* Okay, so the user matches. */
char *pass = strtok(NULL, ", ");
if (!pass || strcmp(pass, password)) {
    /* Invalid. */
    break;
}

Of course this code assumes you already trust the strings user and password and it's also untested.

OTHER TIPS

I don't want to sound pedantic but when you open a file, You should add an if to test if the file could be opened or not. Something like:

if ( ( data = fopen( "password.csv", "r+" ) ) != NULL ){
    printf( "The file couldn't be opened" );
}
else{
   .
   .
   .
}

Or at least something to notice if the file couldn't be opened to trace the problem.

The biggest problem you have is that strtok(verifyUser, ", ") will split the input line on both commas AND SPACES, so if any of your fields contain spaces (such as a real name), they'll be split into multiple fields.

The usual way to use strtok is in a loop:

for (token = strtok(inputLine, ","); token; token = strtok(0, ",")) {
    /* do something with token */

First thing you are not reading it line by Line..you are copying 50 characters into verifyUser
so it aint gonna work for longer than buffer size (50) length. fgets(verifyUser, 50, data)

to readline use something like this...

getline(data, yourVariable, '\n');

and then you can do is..

ptr = strtok(yourVariable, ", ");
// now u have to iterate through `ptr` to get all the sub-strings(split-ed using parameter ',')
while(ptr !=NULL){
     if(strcmp(ptr, user)){
         // do stuff here like `break;` etc
     }
}

btw it a good practice if u do error checking... like what-if fopen() fails (then you should not run rest of the code..)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top