【Linux文件操作】使用c语言实现cp命令

一、实验内容

编写程序,实现 cp 命令的功能。被复制的文件名与复制出的新文件由用户指定。
调用方法:“你编写的程序名 被复制文件名 复制出的文件名”。要求程序有一定的健壮性,即对用户错误调 用及其他错误要有处理和反馈。(提示:可以使用 man 手册查看具体的系统调用,e.g., man 2 open)。

二、思路

1、了解c语言中main函数

在最新的c99标准中,有两种定义方式:

  • 带参数形式

int main( int argc, char *argv[] ) /* 带参数形式 */
{
    ...
    return 0;
}

main函数的三个参数:

  • 第一个参数 argc ,用于存放命令行参数的个数。

  • 第二个参数 argv,是个字符指针的数组,每个元素都是一个字符指针,指向一个字符串,即命令行中的每一个参数。

  • 第三个参数 envp ,也是一个字符指针的数组,这个数组的每一个元素是指向一个环境变量的字符指针。

  • 无参数形式

int main( void )  /* 无参数形式 */
{
    ...
    return 0;
}

2、了解系统调用open

2.1 使用man手册查询open

[root@username ~]# man 2 open

man手册查询open系统调用

2.2 open调用

1. 概要SYNOPSIS

       #include <sys/types.h>
       #include <sys/stat.h>
       #include <fcntl.h>
       int open(const char *pathname, int flags);
       int open(const char *pathname, int flags, mode_t mode);
       int creat(const char *pathname, mode_t mode);

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、代码思路

  1. 通过main函数中参数的个数来判断用户的输入是否正确并反馈
  2. 打开需要复制的文件,创建空白文件,并逐行将内容复制
  3. 判断文件是否正确打开或创建,解决文件名可能存在或无权限打开等情况

三、代码

#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<string.h>
#include<stdlib.h>

int main(int argc,char** argv,char** environ)
{
    if(NULL==argv[1])//argv[0]是运行的程序名 ,所以我们直接判断argv[1]是否为空就能知道参数是否足够。
    {
        puts("Args are needed!\n");
        return 0;
    }
    if(NULL!=argv[3])//如果argv[3]不为空,说明有第三个参数,而cp指令只需要有2个参数。
    {
        puts("Too many args\n");
        return 0;
    }
    int fd=open(argv[1],O_RDWR|O_CREAT,S_IRWXU);//打开要拷贝的文件
    if(fd<0)
    {
        puts("no permission");
        return 0;
    }
    int fd2=open(argv[2],O_RDWR|O_CREAT|O_EXCL,S_IRWXU);//建立一个新的空白文件
    if(fd2<0)
    {
        puts("file are exist,press y to recover");
        char ch;
        ch=getchar();
        if(ch == 'y')
        {
            fd2=open(argv[2],O_RDWR|O_CREAT,S_IRWXU);
            if(fd2<0)
            {
                puts("no permission");
                return 0;
            }
        }
        else
            return 0;
    }
    int count=1;
    for(int i=0;count>0;i++)
    {
        char buf;
        count=read(fd,&buf,sizeof(buf));
        write(fd2,&buf,sizeof(buf));
    }//将被拷贝的文件的内容写入到空白文件中
    close(fd);//关闭被拷贝的文件
    close(fd2);//关闭新的文件
    return 0;
} 
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,519评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,842评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,544评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,742评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,646评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,027评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,513评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,169评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,324评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,268评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,299评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,996评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,591评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,667评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,911评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,288评论 2 345
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,871评论 2 341

推荐阅读更多精彩内容