read函数
read的用法
从fd这个文件描述符里面读,读到buf去,读count个。
返回值
成功的话,返回成功读到的字节数。失败的话,返回-1,并且errno记录错误的原因。
write函数
write的用法
写fd这个已经成功打开的文件,来源于buf中,写count个。
返回值
成功的话,返回成功写入的字节个数。失败的话,返回值是-1。
lseek函数
lseek的用法
对文件描述符为fd的文件进行定位,偏移量为offset,相对偏移位置为whence。
返回值
成功的话,返回从文件开始处到当前文件位置指针的距离。
代码实例
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.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...\n");
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()");
break;
}
if (len == 0)
break;
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);
exit(0);
}