Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP]task 3wjzlwz #101

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions 003_copy/wjzlwz/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
all: mycp
./mycp ../README.md file

mycp: mycp.c
gcc -o $@ $<

clean:
rm -rf mycp

.PHONY:all
.PHONY:clean

15 changes: 15 additions & 0 deletions 003_copy/wjzlwz/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
### 1. 如果 `open` 或者另外几个相关的系统调用执行出错,你如何找出出错的原因?

答:google错误打印的信息,也可以使用man指令查看相关错误信息含义。

### 2. 你觉得学习本篇有什么困难?

答:没有太大困难。

### 3. 你觉得掌握文件 IO 还能做些什么事情?

答:可以利用系统调用对磁盘的文件自定义操作。

### 4. 在你的终端执行命令 `ps`,你会看到你当前 bash 的 PID 号(第一行),记下这个 PID,然后再执行 `lsof -p ${PID}`,注意了,请把 ${PID} 替换成你看到的 PID。接下来你会看到 `lsof` 执行的输出结果。描述你看到的现象,你发现了什么

答:看到bash打开的文件,包含进程名(bash),进程id,用户,文件描述符,文件类型,磁盘名称,文件大小,索引节点,当前所在文件名。
42 changes: 42 additions & 0 deletions 003_copy/wjzlwz/mycp.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>

#define BUFFERSIZE 1024

int main(int argc, char* argv[]) {
if (argc != 3) {
printf("wrong format");
return -1;
}
int src = open(argv[1], O_RDONLY);
if (src == -1) {
perror("open error");
return -1;
}

int dst = open(argv[2], O_CREAT | O_WRONLY, 0666);
if (dst == -1) {
perror("open error");
return -1;
}

int length = 0;
char buffer[BUFFERSIZE] = {0};

while((length = read(src, buffer, BUFFERSIZE)) > 0) {
if (write(dst, buffer, length) != length) {
perror("write error");
return -1;
}
}
if (length < 0) {
perror("read error");
return 1;
}
close(src); // 关闭文件
close(dst);
return 0;
}