I want to print the contents of a .txt file to the command line like this:
main() { int fd; char buffer[1000]; fd = open("testfile.txt", O_RDONLY); read(fd, buffer, strlen(buffer)); printf("%sn", buffer); close(fd); }
The file testfile.txt looks like this:
line1 line2 line3 line4
The function prints only the first 4 letters line
.
When using sizeof
instead of strlen
the whole file is printed.
Why is strlen
not working?
Advertisement
Answer
When using sizeof instead of strlen the whole file is printed. Why is strlen not working?
Because how strlen works is it goes through the char array passed in and counts characters till it encounters 0. In your case, buffer
is not initialized – hence it will try to access elements of uninitialized array (buffer
) to look for 0, but reading uninitialized memory is not allowed in C. Actually you get undefined behavior.
sizeof
works differently and returns the number of bytes of the passed object directly without looking for a 0 inside the array as strlen
does.
As correctly noted in other answers read will not null terminate the string for you so you have to do it manually or declare buffer
as:
char buffer[1000] = {0};
In this case printing such buffer using %s
and printf
after reading the file, will work, only assuming read didn’t initialize full array with bytes of which none is 0.
Extra:
Null terminating a string means you append a 0 to it somewhere. This is how most of the string related functions guess where the string ends.