- read/write函数
#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);
// read() attempts to read up to count bytes from file
// descriptor fd into the buffer starting at buf.
ssize_t write(int fd, const void *buf, size_t count);
// write() writes up to count bytes from the buffer
// starting at buf to the file referred to by the file descriptor fd.
- 编程实现简单的cp功能
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<fcntl.h>
int main(int argc, char* argv[])
{
char buf[1024];
int n = 0;
int fd1, fd2;
fd1=open(argv[1],O_RDONLY);
if(fd1 == -1){
perror("open argv1 error");
exit(2);
}
fd2=open(argv[2],O_WRONLY | O_CREAT | O_TRUNC, 0644);
if(fd1 == -1){
perror("open argv2 error");
exit(1);
}
while((n=read(fd1,buf,1024)) != 0){
if(n<0){
perror("read error");
break;
}
write(fd2,buf,n);
}
close(fd1);
close(fd2);
return 0;
}
3.错误处理函数
1、与 errno 相关
printf("xxx error: %d\n", errno);
char* *strerror(int errnum);
printf("xxx error: %s\n", strerror(errno));
2、perror函数
void perror(const char* s);
perror("xxx error");
这篇博客介绍了如何利用C语言中的read和write系统调用实现文件的复制功能。程序首先打开源文件和目标文件,然后通过不断读取源文件内容并写入目标文件,完成复制过程。在遇到错误时,程序会使用errno和perror函数进行错误处理,显示详细的错误信息。

693

被折叠的 条评论
为什么被折叠?



