c - read() return extra characters from file -
i trying read text file print.. while trying if give char buffer size returns character ..
#include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include <fcntl.h> int main(){ int fd = open("text.txt",o_rdonly); char cbuffer[100]; int =0; if(fd>0){ puts("file open"); ssize_t len = read(fd,cbuffer,sizeof(cbuffer)); =printf("%s",&cbuffer); printf("\n return data count %d",a); } return 0; } if instead of
ssize_t len = read(fd,cbuffer,sizeof(cbuffer)); to
ssize_t len = read(fd,cbuffer,10); returns 10 chars . can explain why happening?
this happens because, read() not null-terminate output. need null-terminate destination buffer before using string.
basically passing non-null terminated char array printf() argument %s creates undefined behavior there can out of bound memory access.
one way of achieving 0-initialize destination. way, considered null-terminated after valid values read , stored read(). like
char cbuffer[100] = {0}; can help.
that said, change
printf("%s",&cbuffer); to
printf("%s",cbuffer); as %s expects pointer null-terminated array of chars. when pass array name function, decays pointer first element, should ok.
Comments
Post a Comment