高士涛 - 学习日报

姓名

高士涛

日期

2023/04/28

部门

云服务业务部

导师

王晓明

学习工作内容

基于C的文件复制

1文件复制C程序源码:

#include<stdio.h>

#include<unistd.h>

#include<sys/types.h>

#include<sys/stat.h>

#include<fcntl.h>

int main() {

const char* pathName="myCFile01";

int in,out,flag;

char buffer[1024];

//打开源文件,赋予读权限

in=open("//home//testC//cfile01",O_RDONLY,S_IRUSR);

if(in==-1) {

printf(" 打开文件cfile01失败 !\n");

return -1;

}

//创建目标文件

out = creat(pathName,S_IWUSR);

if(in==-1) {

printf("创建文件myCFile01失败!\n");

return -1;

}

else{

printf("创建文件myCFile01成功!\n");

}

//从源文件中读数据到buffer,再将buffer的数据写到目标文件中

while((flag=read(in,buffer,1024))>0) {

write(out,buffer,flag);

}

//释放资源

close(in);

close(out);

printf("复制文件cfile01myCFile01完成!\n");

return 0;

}

 

2、在自己的工作目录创建C程序源码文件“fileCopy.c”:

 

3、使用vi命令进入C程序源码文件编辑视图,将写好的C程序源码粘贴进去:

 

4、生成可执行文件“a.out”:

 

5、运行可执行文件“a.out”,根据结果可知程序运行成功,源文件与目标文件比较结果显示一致,文件复制成功:

 

6、删掉生成的目标文件“myCFile01”:

 

7、从C语言编写的源代码,到生成可执行程序文件的分步编译:

 

8、运行可执行程序“fileCopy”,

 

9、文件比较结果可看出C程序成功运行,文件复制成功:

 

10open第三个参数一般用法:

    if((to_fd = open(to, O_WRONLY|O_CREAT, S_IRUSR|S_IWUSR)) == -1)

    {

        //db_error("Open %s Error:%s\n", to, strerror(errno));

        //close(from_fd);

        //return -1;

    }

 

S_IRUSR

  Permits the file's owner to read it.

  允许文件的所有者阅读它。

 

S_IWUSR

  Permits the file's owner to write to it.

  允许文件所有者写它。

 

S_IRGRP

  Permits the file's group to read it.

  允许文件组读取它

 

S_IWGRP

  Permits the file's group to write to it.

  允许文件组编写它        //return -1;

    }

 

|是位或运算符。

man creat

 

 

遗留问题

 

明日计划

 继续深入学习