c - Why read() from a file always endwith a breakline -


test.c

int main() {     int fd = open("/test/aaa",o_rdonly);     char * str;     int len;     str = (char*)malloc(sizeof(char));     len = read(fd,str,100);     close(fd);     printf("%s\n",str);     free(str);     str = null;     return 0; } 

output like:

$echo 300 > /test/aaa $gcc test.c -o test $./test 300  $ 

why there's line break output here? there safe way ride of ? or did use read() in wrong way? thanks!

because there's newline in file see if did dump of like:

od -xcb /test/aaa 

the reason it's in file because put there: default behaviour of echo write give plus newline character.

if don't want newline character, use:

echo -n 300 >/test/aaa 

in addition, haven't allocated enough space in malloc store other single character, might want try:

str = malloc (100); 

you'll noticed don't cast return value of malloc - it's bad habit in c, capable of implicitly casting void * returned other pointer. can hide subtle errors if explicitly cast.

it's given sizeof(char) always 1 in c don't need multiply anything.


to honest, if want line-based file input, read wouldn't first choice. there far better options fgets doing sort of thing.


Comments

Popular posts from this blog

Change php variable from jquery value using ajax (same page) -

Pull out data related to my apps from Android Play Store and iOS App Store -

How can I fetch data from a web server in an android application? -