I have a very simple question regarding file write.
I have this program:
char buf[20];
size_t nbytes;
strcpy(buf, "All that glitters is not gold\n");
fd= open("test_file.txt",O_WRONLY);
write(fd,buf,strlen(buf));
close(fd);
What am confused is when I open the file test_file.txt after running this program I see some characters like ^C^@^@^@^^^@ after the line “All that glitters is not”: Notice that portion of the buf is not written and those characters appear instead. Why is that so?
You’re writing more than 19 chars in that buffer. Once you’ve done that, the behavior of your program is undefined. It could do whatever it wants.
Allocate a large enough buffer. It has to be able to fit all the letters plus a terminating
0if you need to be able to treat it as a C string.