Linux

Linux系统编程

文件拷贝

代码位置:D:\Linux\myClass\cpfile

0.创建一个文件夹cpfile

1.编写main.c函数,存放于cpfile中

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

// argv[0] argv[1]  argv[2]
// ./mucp  srcfile  dstfile
// 实现将文件srcfile拷贝为文件dstfile
// srcfile为源文件   dstfile为要新建的文件
int main(int argc, char *argv[])
{
    // 定义一个缓冲区
    char buf[512]={0};

    int fd_src, fd_dst;
    //  打开源文件只读形式
    fd_src = open(argv[1], O_RDONLY);
    if (fd_src == -1)
    {
        perror("open src error");
        return -1;
    }
    // 创建新建的文件为只写方式
    fd_dst = open(argv[2], O_WRONLY | O_CREAT, 0755);
    if (fd_dst == -1)
    {
        perror("open dst error");
        return -1;
    }

    // 拷贝文件的过程
    int count;
    while (1)
    {
        count = read(fd_src, buf, 512);
        if(count==0){
            break;
        }
        write(fd_dst,buf,count);
        memset(buf,0,512);
    }

    close(fd_src);
    close(fd_dst);
}

2.编译main.c,编译后的结果为main

gcc -o main main.c

在这里插入图片描述

3.在cpfile夹下创建一个文件test.txt

4.执行main

//     原文件    目标文件
./main test.txt newtest.txt

在这里插入图片描述

求文件内容的长度

代码位置:D:\Linux\myClass\filesize

0.创建一个文件夹filesize

1.编写main.c函数,存放于filesize中

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

//  argv[0]   argv[1] 
// ./filesize filename
// 实现获取filename文件的大小(以字节为单位)

int main(int argc, char *argv[])
{
    
    int fd_src;
    //  打开源文件只读形式
    fd_src = open(argv[1], O_RDONLY);
    if (fd_src == -1)
    {
        perror("open src error");
        return -1;
    }

    long int size;
    size=lseek(fd_src,0,SEEK_END);
    printf("%s size:%ld\n",argv[1],size);
    
    close(fd_src);
    
}

2.编译mian.c,编译后的结果为main

gcc -o main main.c

3.在cpfile夹下创建一个文件test.txt,并写入内容

4.执行main

//      文件名
./main test.txt

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值