I am trying to read text from file to print.. While trying if I give the char buffer size it returns some extra character ..
#include
#include &
This happens because, read()
does not null-terminate the output. You need to null-terminate the destination buffer before using it as a string.
Basically passing a non-null terminated char
array to printf()
as the argument to %s
creates undefined behavior as there can be out of bound memory access.
One way of achieving this is to 0
-initialize the destination. That way, it will be considered null-terminated after the valid values read and stored by read()
. Something like
char cbuffer[100] = {0};
can help.
That said, change
printf("%s",&cbuffer);
to
printf("%s",cbuffer);
as %s
expects a pointer to a null-terminated array of char
s. When you pass the array name to a function, it decays to the pointer to the first element, so you should be ok.