程序笔记   发布时间:2022-07-05  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了利用文件I/O与标准I/O进行文件的拷贝(c语言)大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
  1 /*
  2  * 需求描述:分别使用文件IO,标准字符、标准行、标准块IO实现文本文件的拷贝功能
  3  * 思,如果是普通的图片、视频文件,上述拷贝哪些可以用,哪些不可以用
  4  * */
  5 #include <stdio.h>
  6 #include <sys/types.h>
  7 #include <sys/stat.h>
  8 #include <fcntl.h>
  9 #include <unistd.h>
 10 
 11 
 12 
 13 /*
 14  * 利用文件IO的方式,实现2个文件的拷贝
 15  * */
 16 int copy_by_fileIO(const char *dest_file_name, const char *src_file_name) {
 17     int fd1,fd2;
 18     int len;
 19 
 20     //打开文件
 21     fd1 = open(src_file_name,O_RDONLY);
 22     fd2 = open(dest_file_name,O_WRONLY);
 23 
 24     //获得文件大小,并且将当前位置移到开头
 25     len = lseek(fd1, 0, SEEK_END);
 26     lseek(fd1,0,SEEK_SET);
 27 
 28     unsigned char buf[len];
 29 
 30     //读取fd1中的内容
 31     read(fd1,&buf,len);
 32 
 33     //写入内容到fd2
 34     write(fd2,&buf,len);
 35 
 36     //关闭文件
 37     close(fd1);
 38     close(fd2);
 39 }
 40 
 41 /*
 42  * 利用标准IO的字符IO,实现2个文件的字节拷贝
 43  * */
 44 int copy_by_char(const char *dest_file_name, const char *src_file_name) {
 45     FILE *fp1,*fp2;
 46     int ch;
 47 
 48     fp1 = fopen(src_file_name,"r");
 49     fp2 = fopen(dest_file_name,"w");
 50 
 51     ch = fgetc(fp1);
 52 
 53     while(ch != EOF){
 54         fputc(ch,fp2);
 55         ch = fgetc(fp1);
 56     }
 57 
 58     fclose(fp1);
 59     fclose(fp2);
 60 }
 61 
 62 /*
 63  * 利用标准IO的行IO,实现2个文件的按行拷贝
 64  * */
 65 int copy_by_line(const char *dest_file_name, const char *src_file_name) {
 66     FILE *fp1,*fp2;
 67     char *res;
 68     char buf[1024];
 69 
 70     fp1 = fopen(src_file_name,"r");
 71     fp2 = fopen(dest_file_name,"w");
 72 
 73     res = fgets(buf,sizeof(buf),fp1);
 74 
 75     while(res){
 76         fputs(buf,fp2);
 77         res = fgets(buf,sizeof(buf),fp1);
 78     }
 79 
 80     fclose(fp1);
 81     fclose(fp2);
 82 }
 83 
 84 /*
 85  * 利用标准IO的块IO,实现2个文件的块拷贝
 86  * */
 87 int copy_by_block(const char *dest_file_name, const char *src_file_name) {
 88     FILE *fp1,*fp2;
 89     char res[3] = {0};
 90     int len;
 91 
 92     fp1 = fopen(src_file_name,"r");
 93     fp2 = fopen(dest_file_name,"w");
 94 
 95     fseek(fp1,0,SEEK_END);
 96     len = ftell(fp1);
 97     fseek(fp1,0,SEEK_SET);
 98 
 99     printf("len:%d",len);
100 for(int i=0;i<len;i++) {
101     fread(res, sizeof(char), 1, fp1);
102     fwrite(res, sizeof(char), 1, fp2);
103 }
104     fclose(fp1);
105     fclose(fp2);
106 }
107 
108 int main() {
109     char *src_file_path = "./profile";
110     char *dest_file_path = "./test_profile";
111     copy_by_block(dest_file_path,src_file_path);
112     return 0;
113 }

 @H_450_577@

大佬总结

以上是大佬教程为你收集整理的利用文件I/O与标准I/O进行文件的拷贝(c语言)全部内容,希望文章能够帮你解决利用文件I/O与标准I/O进行文件的拷贝(c语言)所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。