#一、实验内容
编写程序,实现 cp 命令的功能。被复制的文件名与复制出的新文件由用户指定。
调用方法:“你编写的程序名 被复制文件名 复制出的文件名”。要求程序有一定的健壮性,即对用户错误调 用及其他错误要有处理和反馈。(提示:可以使用 man 手册查看具体的系统调用,e.g., man 2 open)。
#二、思路
##1、了解c语言中main函数
在最新的c99标准中,有两种定义方式:
- ###带参数形式Code
1
2
3
4
5int main( int argc, char *argv[] ) /* 带参数形式 */
{
...
return 0;
}
main函数的三个参数:
第一个参数 argc ,用于存放命令行参数的个数。
第二个参数 argv,是个字符指针的数组,每个元素都是一个字符指针,指向一个字符串,即命令行中的每一个参数。
第三个参数 envp ,也是一个字符指针的数组,这个数组的每一个元素是指向一个环境变量的字符指针。
###无参数形式
Code1
2
3
4
5int main( void ) /* 无参数形式 */
{
...
return 0;
}##2、了解系统调用open
###2.1 使用man手册查询open
[root@username ~]# man 2 open
###2.2 open调用
####1. 概要SYNOPSIS
1 | #include |
####2. 关键解释
- flags参数部分解释
The argument flags must include one of the following access modes: O_RDONLY, O_WRONLY, or O_RDWR. These request opening the file read-only, write-only, or read/write, respectively.
In addition, zero or more file creation flags and file status flags can be bitwise-or’d in flags. The file creation flags are O_CLOEXEC, O_CREAT, O_DIRECTORY, O_EXCL, O_NOCTTY,O_NOFOLLOW, O_TRUNC, and O_TTY_INIT. The file status flags are all of the remaining flags listed below. The distinction between these two groups of flags is that the file status flags can be retrieved and (in some cases) modified using fcntl(2). The full list of file creation flags and file status flags is as follows:
O_CREAT
If the file does not exist it will be created. The owner (user ID) of the file is set to the effective user ID of the process. The group ownership (group ID) is set either to the effective group ID of the process or to the group ID of the parent directory (depending on file system type and mount options, and the mode of the parentdirectory, see the mount options bsdgroups and sysvgroups described in mount(8)).
O_EXCL
Ensure that this call creates the file: if this flag is specified in conjunction with O_CREAT, and pathname already exists, then open() will fail.When these two flags are specified, symbolic links are not followed: if pathname is a symbolic link, then open() fails regardless of where the symbolic link points to. - mode参数部分解释
mode specifies the permissions to use in case a new file is created. This argument must be supplied when O_CREAT is specified in flags; if O_CREAT is not specified, then mode is ignored. The effective permissions are modified by the process’s umask in the usual way: The permissions of the created file are (mode & ~umask). Note that this mode applies only to future accesses of the newly created file; the open() call that creates a read-only file may well return a read/write file descriptor.
The following symbolic constants are provided for mode:
S_IRWXU 00700 user (file owner) has read, write and execute permission
##3、代码思路
- 通过main函数中参数的个数来判断用户的输入是否正确并反馈
- 打开需要复制的文件,创建空白文件,并逐行将内容复制
- 判断文件是否正确打开或创建,解决文件名可能存在或无权限打开等情况
#三、代码
1 | #include |