I used syscalls read () and write () in my WITHOUT program, including the unistd.h header file in the program. But still, the program works and gives the expected results.
After starting the program, I thought that I would read the man page for read () and write ().
The man 2 page for read () and write () in the SYNOPSIS section mentions that I need to include the unistd.h header file to use read () or write ().
SYNOPSIS
#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);
SYNOPSIS
#include <unistd.h>
ssize_t write(int fd, const void *buf, size_t count);
So, I am surprised how my program worked, although I did not enable unistd.h?
Below is my program. This is a program for copying the contents of the source file to the target file using the read () and write () system calls.
#include<stdio.h>
#include<fcntl.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<stdlib.h>
int main()
{
char buffer[512];
char source[128], target[128];
int inhandle, outhandle;
int bytes;
printf("\nSource File name: ");
scanf("%s",source);
inhandle = open(source, O_RDONLY);
if (inhandle == -1)
{
perror("Error opening source file.\n");
exit(1);
}
printf("\nTarget File name: ");
scanf("%s",target);
outhandle = open(target, O_CREAT | O_WRONLY, 0660);
if (outhandle == -1)
{
perror("Error opening target file.\n");
close(inhandle);
exit(2);
}
while((bytes = read(inhandle, buffer, 512)) > 0)
{
write(outhandle, buffer, bytes);
}
close(inhandle);
close(outhandle);
return 0;
}