I am trying to use the system calls read() and write(). The following program creates a file and writes some data into it. Here is the code..
int main()
{
int fd;
open("student",O_CREAT,(mode_t)0600);
fd=open("student",O_WRONLY);
char data[128]="Hi nikhil, How are u?";
write(fd,data,128);
}
Upon the execution of the above program i got a file with name student created with size as 128 bytes.
int main()
{
int fd=open("student",O_WRONLY);
char data[128];
read(fd,data,128);
cout<<(char*)data<<endl;
}
But the output i get is junk characters….why is this so?
I wrote a small read program to read data from the file. Her is the code.
But the output
You’re not checking whether
read()returns an error. You should do so, because that’s probably the case with the code in your question.Since you’re opening the file write-only in the first place, calling
read()on it will result in an error. You should open the file for reading instead: