NAME
読み取り-ファイル記述子から読み取ります
概要
#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);
説明
read()は、ファイル記述子fdからbufで始まるバッファに最大カウントバイトを読み取ろうとします。
戻り
値成功すると、読み取られたバイト数が返されます(ゼロはファイルの終わりを示します)。
エラーの場合、-1が返されます。
NAMEwrite-
ファイル記述子への書き込み
概要
#include <unistd.h>
ssize_t write(int fd, const void *buf, size_t count);
説明
write()は、bufが指すバッファーから、ファイル記述子fdによって参照されるファイルに最大カウントバイトを書き込みます。
戻り
値成功すると、書き込まれたバイト数が返されます(ゼロは何も書き込まれなかったことを示します)。
エラーの場合、-1が返されます。
名前
のlseek -再配置の読み取り/書き込みファイルオフセット
概要
#include <sys / types.h>
#include <unistd.h>
off_t lseek(int fd, off_t offset, int whence);
開いたファイルを再配置するための説明、相対位置理由:
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.
戻り値
正常に完了すると、lseek()は、ファイルの先頭からバイト単位で測定された結果のオフセット位置を返します。エラーの場合、値(off_t)-1が返され、エラーを示すためにerrnoが設定されます。
実験1は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);
}