Reputation: 21019
I am trying to scan a file using fscanf
and put the string into an char array of size 20 as follows:
char buf[20];
fscanf(fp, "%s", buf);
The file fp
currently contains: 1 + 23
.
I am setting a pointer to the first element in buf
as follows:
char *p;
p = buf;
Printing buf
, printf("%s", buf)
yields only 1
. Trying to increment p
and printing prints out rubbish as well (p++; printf("%c", *p)
).
What am I doing wrong with fscanf
here? Why isn't it reading the whole string from the file?
Upvotes: 1
Views: 353
Reputation: 63797
fscanf
(and related functions) with the format-string "%s" will try to read as many characters as it can without including a whitespace, in this case it will find the first character (1
) and store it, then it will hit a space () and therefore stop searching.
If you'd like to read the whole line at once consider using fgets
, it is also safer to use since you need to specify the size of your destination buffer as one of it's arguments.
fgets
will try to read at maximum length-of-buffer minus 1 characters (last byte is saved for the trailing null-byte), it will stop at either reading that many characters, hitting a new-line or the end of the file.
fgets (buf, 20, fp);
Links to documentation
Upvotes: 7