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
First of all you should print every character of strings you want to compare as hex/dec values. It is possible strings contain characters that are printed in console but you can not see them. Visible output may look the same but it can still differs. Printing (for example) hex values will show you exactly what is inside strings.
Then if output will be the same for both strings and strcmp will still return something other than 0 you should worry (but I am sure it won't be :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.