forked from mit-pdos/xv6-public
-
Notifications
You must be signed in to change notification settings - Fork 12
/
mv.c
executable file
·77 lines (66 loc) · 1.59 KB
/
mv.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/*
*文件名称:mv.c
*创建者:程嘉梁
*创建日期:2018/04/14
*文件描述:实现移动文件的功能(mv命令)
*历史记录:整合自三字班方案二
*/
#include "types.h"
#include "stat.h"
#include "user.h"
#include "fcntl.h"
#include "fs.h"
int main(int argc,char* argv[]){
const int bufSize = 128;
char buf[bufSize];
int length = 0;
if(argc == 1 || argc == 2){
printf(2, "Usage: mv src_file dst_file\n");
exit();
}
int fp_src = open(argv[1],O_RDONLY);
if(fp_src == -1){
printf(2,"mv cannot open source file %s\n", argv[1]);
close(fp_src);
exit();
}
struct stat st;
fstat(fp_src,&st);
if(st.type == T_DIR){
printf(2,"mv cannot move directory %s, it can move files\n",argv[1]);
close(fp_src);
exit();
}
//if dst_file is a directory which ends up with '/', add file name from src_file to directory
char filename[bufSize];
strcpy(filename,argv[2]);
int src_len = strlen(argv[1]);
int dst_len = strlen(argv[2]);
if(argv[2][dst_len-1] == '/'){
int index;
for(index = src_len-1;index >= 0;index--){
if(argv[1][index] == '/'){
break;
}
}
index++;
strcpy(&filename[dst_len],&argv[1][index]);
}
int fp_dst = open(filename,O_WRONLY | O_CREATE);
if(fp_dst == -1){
printf(2,"mv cannot open destination file %s\n", filename);
close(fp_dst);
close(fp_src);
exit();
}
while((length = read(fp_src,buf,bufSize)) > 0){
write(fp_dst,buf,length);//此处进行修正,将bufSize改正为length
}
close(fp_dst);
close(fp_src);
//delete file_src
if(unlink(argv[1]) < 0){
printf(2,"mv failed to delete file : %s\n", argv[1]);
}
exit();
}