分享

open文件操作

 海漩涡 2016-07-24

#include <stdio.h>
#include <fcntl.h>

#define BUFSIZE 50
#define PERMS 0666 /* 对所有者、所有者组、其他成员均可读 */


/*
    【1】
    unlink(char* name) // 删除name文件,对应于remove命令

    【2】
    #include <sys/types.h>
    #include <unistd.h>
    origin: 
    SEEK_SET 开头位置 
    SEEK_CUR 当前位置
    SEEK_END 末尾位置
    long lseek(int fd, long offset, int origin);


    【3】
    #include <sys/types.h>
    #include <sys/stat.h>
    #include <fcntl.h>

    
    int open(const char *pathname, int flags);

    mode:  O_RDONLY, O_WRONLY, O_RDWR
    int open(const char *pathname, int flags, mode_t mode);

    // creat() is equivalent to open() with flags equal to O_CREAT|O_WRONLY|O_TRUNC
    int creat(const char *pathname, mode_t mode);
*/



/* cp函数: 将f1复制到f2 */
int main(int argc ,char *argv[])
{
    int f1, f2, n;
    char buf[BUFSIZE];

    if(argc != 3)
        printf("Usage: cp from to");

    if((f1 = open(argv[1], O_RDONLY, 0)) == -1)
        printf("cp: can't open %s", argv[1]);

    if((f2 = creat(argv[2], PERMS)) == -1)
        printf("cp: can't creat %s,mod %03o", argv[2], PERMS);

    while((n = read(f1, buf, BUFSIZE)) > 0)
    {
        if(write(f2, buf, n) != n)
            printf("cp: write error on file %s", argv[2]);
    }

    close(f1);
    close(f2);
    
    return 0;
}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多