Linux system programming 14 The realization of system calls IO-read, write, lseek and mycopy

NAME
read - read from a file descriptor

SYNOPSIS
#include <unistd.h>

   ssize_t read(int fd, void *buf, size_t count);

DESCRIPTION
read() attempts to read up to count bytes from file descriptor fd into the buffer starting at buf.

RETURN VALUE
On success, the number of bytes read is returned (zero indicates end of file).

On error, -1 is returned,


NAME
write - write to a file descriptor

SYNOPSIS
#include <unistd.h>

   ssize_t write(int fd, const void *buf, size_t count);

DESCRIPTION
write() writes up to count bytes from the buffer pointed buf to the file referred to by the file descriptor fd.

RETURN VALUE
On success, the number of bytes written is returned (zero indicates nothing was written).
On error, -1 is returned.


NAME
lseek - reposition read/write file offset

SYNOPSIS
#include <sys/types.h>
#include <unistd.h>

   off_t lseek(int fd, off_t offset, int whence);

DESCRIPTION
to relocate the opened file, relative position whyce:

   SEEK_SET
          The offset is set to offset bytes.

   SEEK_CUR
          The offset is set to its current location plus offset bytes.

   SEEK_END
          The offset is set to the size of the file plus offset bytes.

RETURN VALUE
Upon successful completion, lseek() returns the resulting offset location as measured in bytes from the beginning of the file. On error, the value (off_t) -1 is returned and errno is set to indicate the error


Experiment 1 implement mycpy

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#define BUFSIZE 1024

int main(int argc,char *argv[])
{
	int sfd,dfd;
	char buf[BUFSIZE];
	int len,ret,pos;

	if(argc < 3)
	{
		fprintf(stderr,"Usage:%s <src_file> <dest_file>\n",argv[0]);
		exit(1);
	}
	
	sfd = open(argv[1],O_RDONLY);
	if(sfd < 0)
	{
		perror("open()");
		exit(1);
	}
	dfd = open(argv[2],O_WRONLY | O_CREAT,O_TRUNC,0600);
	if(dfd < 0)
	{
		close(sfd);
		perror("open()");
		exit(1);
	}

	while(1)
	{
		len = read(sfd,buf,BUFSIZE);
		if(len < 0)
		{
			perror("read()");
		}
		if(len == 0)
			break;

		//确保写进去 len 个字节
		pos = 0;
		while(len > 0)
		{
			ret = write(dfd,buf+pos,len);
			if(ret < 0)
			{
				perror("write()");
				exit(1);
			}
			pos += ret;
			len -= ret;
		}

	}
	
	close(dfd);
	close(sfd);
		
}

Guess you like

Origin blog.csdn.net/LinuxArmbiggod/article/details/105902495