免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2086 | 回复: 3
打印 上一主题 下一主题

怎么写一个完美的cp [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2007-09-08 20:49 |只看该作者 |倒序浏览
我写了一个简单的复制文件的例子,
/* copy file */
#include <sys/types.h>
#include <stdio.h>
#include <string.h>

#define BUF_SIZE 1024

int main(void)
{
    char buf[BUF_SIZE];
    memset(buf, 0, BUF_SIZE);
    FILE *source,  *backup;

    if ((source = fopen("source.dat", "rb")) == NULL)
    {
        printf("Error in opening file.\n");
        exit(1);
    }

    if ((backup = fopen("backup.dat", "wb")) == NULL)
    {
        printf("Error in creating file.\n");
        exit(1);
    }

    while (feof(source) == 0)
    /* haven't reached the end of the file */
    {
        if (fread(buf, sizeof(char), sizeof(buf), source) < 1)
        /* less than the length of  buf, */
            if (feof(source) != 0)
        /* but haven't reached the end of file, which says a error happend */
        {
            printf("Error in reading file.\n");
            break;
        }
        if (fwrite(buf, sizeof(char), sizeof(buf), backup) < 1)
        /* the same like above */
        {
            if (feof(backup) != 0)
            {
                printf("Error in wrinting file.\n");
                break;
            }
        }
    }

    if (fclose(source) == EOF)
    {
        printf("Error in close file.\n");
        exit(1);
    }
    if (fclose(backup) == EOF)
    {
        printf("Error in close file.\n");
        exit(1);
    }
}
       但相信里面有很多bug,有谁有完美的复制文件的例子?
     顺便问一下,我想自己写一些linux下如cp ,rm , 等小工具,想做个借鉴,有没有类似源代码可以看?

论坛徽章:
0
2 [报告]
发表于 2007-09-08 21:42 |只看该作者
我会考虑用mmap
----------------------------------------------------------------

论坛徽章:
0
3 [报告]
发表于 2007-09-09 09:17 |只看该作者
何为完美?

cp 和 rm 的代码,请看 binutils 。

论坛徽章:
95
程序设计版块每日发帖之星
日期:2015-09-05 06:20:00程序设计版块每日发帖之星
日期:2015-09-17 06:20:00程序设计版块每日发帖之星
日期:2015-09-18 06:20:002015亚冠之阿尔艾因
日期:2015-09-18 10:35:08月度论坛发贴之星
日期:2015-09-30 22:25:002015亚冠之阿尔沙巴布
日期:2015-10-03 08:57:39程序设计版块每日发帖之星
日期:2015-10-05 06:20:00每日论坛发贴之星
日期:2015-10-05 06:20:002015年亚冠纪念徽章
日期:2015-10-06 10:06:482015亚冠之塔什干棉农
日期:2015-10-19 19:43:35程序设计版块每日发帖之星
日期:2015-10-21 06:20:00每日论坛发贴之星
日期:2015-09-14 06:20:00
4 [报告]
发表于 2007-09-10 19:24 |只看该作者
原帖由 swordfish.cn 于 2007-9-9 09:17 发表
何为完美?

cp 和 rm 的代码,请看 binutils 。

cp 和 rm 的代码在 coreutils 里面; binutils 里面是一些 assembler 之类的东西.
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP