Read
Read () is a system call function. Used to read the specified length of data from a file into the BUF.
Header files to include when using Read (): <unistd.h>
Function Prototypes:
ssize_t Read (int fd, void *buf, size_t count);
ssize_t is the data type defined by typedef in the system header file, which is equivalent to signed int.
Parameters:
FD: The file descriptor of the file from which to read the content.
Count: The number of file bytes expected to be read.
return value:
The number of bytes read was successfully returned, 0 was read to the end of the file, and 1 was returned with an error.
Write
Write () is a system call function that writes the contents of BUF to a file.
Use the Write () function to include the header file <unistd.h>.
Function Prototypes:
ssize_t Write (int fd, char *buf, size_t count)
Parameters:
FD: The file descriptor of the file from which to read the content.
Count: The number of file bytes expected to be read.
return value:
The write successfully returns the number of bytes actually written, and the error returns-1.
It has to be said that the common reason for returning 1 is that the disk space is full and exceeds the file length of a given process.
Use Read (), write () to complete the file copy:
1#include <unistd.h>2intMainintargcChar*argv[])3 {4 intFS = open (argv[1], o_rdonly);//Open the source file you want to copy5if(fs = =-1)6 {7Perror ("Open source File");8return-1;9 }TenintFD = open (argv[1], O_rdonly | O_creat | O_EXCL,0666);//Create the target file to be copied, and exit if the file already exists Oneif(FD <0) A { -Perror ("Open dest File"); -return-1; the } - - Charbuf[ +] = {0}; -intcount; + while(count = Read (FS, buf,sizeof(BUF))) >0)//read data from a source file and write to the destination file - { + Write (FD, buf, strlen (BUF)); A } at Close (fs); - Close (FD); -return 0; -}
Read (), Write ()