Reputation: 303
I want to fscanf a csv file which is a output of fprintf, I set the same format but it didn't work, which means when I use that function to fscanf the file I just made, it didn't succuss, even didn't get into the while-loop. So, how to modify it to make it work?
part of fprintf
fp = fopen("Out.csv", "w");
fprintf(fp, "%99s,%d,%99s,%99s\n", current->group, current->id, current->name,
current->address);
part of fscanf
fp = fopen("Out.csv", "r");
while (fscanf(fp, "%99s,%d,%99s,%99s\n", group, &id, name, address) == 4) {
head = push_sort(head, group, name, id, address);
printf("%99s", name);
}
Upvotes: 0
Views: 1155
Reputation: 53006
I suspect it's because "%s"
specifier in *scanf()
family stops scanning when it finds a white space, you can tell fscanf()
which specific character to ignore, and it will stop at that character.
I believe the following format string will work
"%99[^,],%d,%99[^,],%99[^,\n]\n"
read this link to find out why I think the pattern will work, search specifically for the [
specifier.
The *scanf()
functions are hard, it's always difficult to make them work correctly, although if you are generating the line and you're sure of what it contains and no surprises will happen, you can trust it to work.
You will be safe if you check the return value, which you do, so if you fail to read lines that you consider valid, then you can try to fgets()
a line from the file, and parse it with strchr()
or strtok()
, I prefer strchr()
because
strlen()
.Upvotes: 1