Linux系统编程实验三:文件编程.docVIP

  • 39
  • 0
  • 约1.05万字
  • 约 8页
  • 2020-01-21 发布于天津
  • 举报
实验三:文件编程 实验目的: 学会创建文件,并制定文件访问属性 学会使用C库函数和Linux系统调用,并理解他们的区别 实验要求: (一)编写应用程序,创建一可读可写的文件 (二)使用库函数,实现文件copy的功能 实验器材: 软件:安装了Linux的vmware虚拟机 硬件:PC机一台 实验步骤: (一)文件创建 1、编写实验代码file_creat.c #include stdio.h #include stdlib.h #include sys/types.h #include sys/stat.h #include fcntl.h void create_file(char *filename) { /*创建的文件具有可读可写的属性*/ if(creat(filename,0666)0) { printf(create file %s failure!\n,filename); exit(EXIT_FAILURE); } else { printf(create file %s success!\n,filename); } } int main(int argc,char *argv[]) { /*判断入参有没有传入文件名 */ if(argc2) { printf(you havent input the filename,please try again!\n); exit(EXIT_FAILURE); } create_file(argv[1]); exit(EXIT_SUCCESS); } 2、编译应用程序file_creat.c 用gcc命令编译file_create.c后生成可执行文件file_creat 3、运行应用程序 运行了该程序后,大家可以发现在当前目录下产生了test.txt文件 4、该实验让大家学习怎样用Linux的系统调用创建一个文件,并设置文件的访问属性,文件操作时Linux应用编程的基础 (二)文件拷贝 1、编写实验代码file_cp.c #include string.h #include strings.h #include stdio.h #include stdlib.h #define BUFFER_SIZE 1024 int main(int argc,char **argv) { FILE *from_fd; FILE *to_fd; long file_len=0; char buffer[BUFFER_SIZE]; char *ptr; /*判断入参*/ if(argc!=3) { printf(Usage:%s fromfile tofile\n,argv[0]); exit(1); } /* 打开源文件 */ if((from_fd=fopen(argv[1],rb))==NULL) { printf(Open %s Error\n,argv[1]); exit(1); } /* 创建目的文件 */ if((to_fd=fopen(argv[2],wb))==NULL) { printf(Open %s Error\n,argv[2]); exit(1); } /*测得文件大小*/ fseek(from_fd,0L,SEEK_END); file_len=ftell(from_fd); fseek(from_fd,0L,SEEK_SET); printf(from file size is=%d\n,file_len); /*进行文件拷贝*/ while(!feof(from_fd)) { fread(buffer,BUFFER_SIZE,1,from_fd); if(BUFFER_SIZE=file_len) { fwrite(buffer,file_len,1,to_fd); } else { fwrite(buffer,BUFFER_SIZE,1,to_fd); file_len=file_len-BUFFER_SIZE; } //写入完成后清空缓冲区 memset(buffer,0,BUFFER_SIZE); } fclose(from_fd); fclose(to_fd); exit(0); } 2、编译应用程序file_cp.c 3、运行应用程序 我们将file_cp.c拷贝为test.c,可以看到运行程序后文件夹出现了test.c和

您可能关注的文档

文档评论(0)

1亿VIP精品文档

相关文档