If I am correct, doing something like:
char *line;
Then I must allocate some memory and assign it to line, is that right? If I am right, the question is the following:
In a line like
while (fscanf(fp,"%[^\n]", line) == 1) { ... }
without assigning any memory to line I am still getting the correct lines and the correct strlen counts on such lines.
So, does fscanf
assign that memory for me and it also places the '\0'
?
I saw no mention about these 2 things on the spec for fscanf
.
The POSIX scanf()
family of functions will allocate memory if you use the m
(a
on some older pre-POSIX versions) format modifier. Note: when fscanf
allocates, it expects a char **
pointer. (see man scanf
) E.g.:
while(fscanf(fp,"%m[^\n]", &line) == 1) { ... }
I would also suggest consuming the newline
with "%m[^\n]%*c"
. I agree with the other answers that suggest using line-oriented
input instead of fscanf
. (e.g. getline
-- see: Basile's answer)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With