Reputation: 15
I've written the example code for read,write system call in linux....Executed without any issues.
As a result,storing the buffer data into a file....
Expected result to be stored in a file is Hello World!..But i'm getting the data in a file like this Hello World!^@
What shall i need to do inorder to get the expected result?
int main(int argc , char *argv[])
{
int fd;
char buff[14];
fd = open("myfile.txt",O_CREAT| O_WRONLY,0777);
if(fd == -1)
{
printf("Failed to open the file to write");
exit(0);
}
write(fd,"Hello World!\n",13);
close(fd);
fd = open("myfile.txt",O_RDONLY,0777);
if(fd == -1)
{
printf("Failed to open the file to read");
exit(0);
}
read(fd,buff,14);
buff[14] = '\0';
close(fd);
printf("Buff is %s\n",buff);
return 0;
}
Upvotes: 0
Views: 74
Reputation: 409196
You declare buff
to be 14 characters, but you write the terminator at position 15. That leads to two instances of undefined behavior: One because you write out of bounds of the array, and one because when you print the buffer you have uninitialized data at position 14.
Upvotes: 2