Reputation: 93
I'm curious why when reading less than 4 bytes from a file, the output is corrupted.
Here is my test file:
user@UnixVM:~/labs$ cat foo.txt
helloworld
And a simple program to read from the file:
int main()
{
int file=0;
if((file=open("foo.txt",O_RDONLY)) < -1)
return 1;
char buffer[11];
read(file,buffer,3);
printf("%s\n",buffer);
return 0;
}
The output is corrupted and may be different between executions:
user@UnixVM:~/labs$ gcc -Wall lab1_4.c -o lab1_4 ; ./lab1_4
hel2
user@UnixVM:~/labs$ gcc -Wall lab1_4.c -o lab1_4 ; ./lab1_4
hel▒
But every time I make number of bytes to read greater or equal to 4 (read(file,buffer,4);
), it works fine.
Upvotes: 2
Views: 257
Reputation: 1
Your output is "corrupted" because buffer
does not contain a NUL terminated C string. Read more about undefined behavior. Be scared (UB sometimes appears to work, and that might explain what you experiment).
So before your call to read
add memset(buffer, 0, sizeof(buffer))
to clear your buffer
. Or initialize it with char buffer[11] ="";
(both are nearly equivalent and likely, with optimizations enabled e.g. gcc -O2
, to generate the same machine code). Since your buffer is 11 bytes long and you read
at most 3 bytes you'll then be sure that it is NUL terminated after the read
.
Be sure to compile with all warnings and debug info (so gcc -Wall -Wextra -g lab1_4.c -o lab1_4
in your case). Read How to debug small programs
Read carefully the documentation of read(2) and of every function you are using. Notice the return count from read
. You should test and use it.
Upvotes: 6