I have a text file with data in the form:
Lee AUS 2 103 2 62 TRUE
Check AUS 4 48 0 23 FALSE
Mills AUS 8 236 0 69 FALSE
I need to each line into a struct like, however I'd like to avoid using fixed length arrays (the problem with fgets as far as I can tell):
struct Data
{
char *sname;
char *country;
int *a;
int *b;
int *c;
int *d;
char *hsisno;
};
I am very new to C. Should I use fscanf, or fgets?
fscanf
stands for "file scan formatted" and user data is about as unformatted as you can get.You should never use naked
"%s"
format strings on data where you don't have absolute control over what can be read.The best solution is to use
fgets
to read a line since this allows you to prevent buffer overflow.Then, once you know the size of your line, that's the maximum size of each string that you will require. Use
sscanf
to your heart's content to get the actual fields.One final thing. It's probably a bit wasteful having
int*
types for the integers, since you know they have a specific maximum size already. I'd use the non-pointer variant, something like:By way of example, here's some safe code:
which reads in your file and stores it in a linked list. It outputs:
at the end, as expected.
I've done a whole series of answers on the pitfalls of using
*scanf
functions on non-controlled data (enteruser:14860 fgets
into the search box above), some of which (here, here and here, for example) include a perennial favourite function of mine,getLine
, for safer user input.