Try fscanf_s
, this function has security enhancements.
http://msdn.microsoft.com/en-us/library/6ybhk9kc(v=vs.90).aspx
Preventing buffer overflow when using fscanf
-
28-06-2022 - |
Domanda
I'm using fscanf to read some values from a CSV file and I want to ensure that the data read into the values will not be too large and cause a buffer overflow.
My csv file has the format int,string,string and my code to read is below (I will fix the while condition later):
while(fscanf(f, "%d,%[^,],%[^,]", &inArray[i].ID, inArray[i].label, inArray[i].brand)/*insert while condition here*/
When using scanf I would specify the length like so to prevent overflow: scanf("%20f", example);
But if I try the same with the above: while(fscanf(f, "%d,%20[^,],%10[^,]", &inArray[i].ID, inArray[i].label, inArray[i].brand)/*insert while condition here*/
I get a crash when the code executes.
Soluzione
Altri suggerimenti
You can't do that with fprintf when reading characters.
I would read the whole line first, e.g., with getline()
, locate the separators (or tokenize the line), and then parse the individual elements.
Btw., the reason for you crash might also be a wrong definition/initialization of inArray
.
OP likely used the wrong width in the fscanf()
.
Although OP did not post details about inArray[i]
let's assume it was
struct {
int ID;
char label[20];
char brand[10];
} inArray[100];
The format should then be
"%d,%19[^,],%9[^,]"
The width of 19 needs to be 1 less than the size of the destination, thus allowing a spot for the '\0'.