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.