Read (), Write ()

Source: Internet
Author: User

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 ()

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.