I am reading in a CSV file using fscanf which has two fields.
datatype_t*read(FILE* fp)
{
char name[66];
char data[1466];
if (fscanf(fp, "%[^,] %[^\n]", name, data) == 2) {
datatype_t *d = (datatype_t*)malloc(sizeof(datatype_t));
d->name = strdup(name);
d->data = strdup(data);
return d;
}
return NULL;
}
CSV file data is as following
Mr Dave,School teacher
Mike,Head
Sachin,staff member
Now I am reading another text file which has data in it.
char buffer[66];
if (fgets(buffer,sizeof buffer, fp) != NULL ) {
keydata_t *k = (keydata_t*)malloc(sizeof(keydata_t));
size_t len = strlen(buffer);
if(buffer > 0 && buffer[len-1] == '\n'){
buffer[--len] = '\0';
}
k->name = strdup(buffer);
return k;
}
return NULL;
}
Data of the txt file looks like this.
Mr Dave
Ron
Mr Tim
Now When I compare the data strings:
new_ptr = root;
while((keyt = read_key(keyfile))!= NULL){
printf("%s\n", keyt->name);
printf("%s\n", root->key);
if(strcmp(keyt->name, root->key) == 0){
printf("match\n");
}
else if(strcmp(keyt->name, root->key) > 0){
printf("not equal\n");
}
else if (strcmp(keyt->name, root->key) < 0){
printf("not equal\n");
}
new_ptr = search(new_ptr, keyt);
}
It keeps printing
not equal
even for Mr Dave where there should be a match. I cant seem to figure out the problem with the two.
From the man fgets
:
fgets
reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A terminating null byte (aq\0aq) is stored after the last character in the buffer.
fscanf
does not store the newline in the buffer.
Please try checking what the last symbol of keyt->name
is and remove it if it is the newline