Linux实验报告_大三上

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

实验三普通文件和目录编程

1.编写程序mycp.c,实现从命令行读入文件的复制功能,用原始文件系统调用。

实验流程图:

实验程序代码:

//mycp.c

#include

#include

#include

#include

#define bufsize 5

int main(int argc,char * argv[])

{

int fd1,fd2;

int i;

char buf[bufsize];

if(argc!=3)

{

printf("argument error\n");

exit(1);

}

fd1=open(argv[1],O_RDONLY);

if(fd1==-1)

{

printf("file %s can not opened\n",argv[1]);

exit(1);

}

fd2=open(argv[2],O_RDWR|O_CREAT);

if(fd2==-1)

{

printf("Can not open file %s\n",argv[2]);

exit(1);

}

while(1)

{

i=read(fd1,buf,bufsize);

write(fd2,buf,i);

if(i!=bufsize) break;

}

close(fd1);

close(fd2);

return 0;

}

Linux环境下运行情况如下:

road@ubuntu:~/桌面/work$ gcc -o cp cp.c

road@ubuntu:~/桌面/work$ ./cp

argument error

Please use:cp file1 file2

road@ubuntu:~/桌面/work$ ./cp a b

其中,a为一文件,b为空文件。

2.编写程序mycat.c,实现文件内容的显示,用原始文件系统调用实现。

//mycat.c

#include

#include

#include

#include

int main(int argc,char* argv[])

{

int fd;

char buffer[100];

int num;

if(argc!=2)

{

printf("usage : %s filename\n",argv[0]);

return 1;

}

if((fd=open(argv[1],O_RDONLY))==-1)

{

perror("cannot open the file");

return 1;

}

while((num=read(fd,buffer,99))>0)

{

buffer[num]='\0';

printf("%s",buffer);

}

close(fd);

return 0;

}

Linux环境下运行情况如下:

road@ubuntu:~/桌面/work$ gcc -o mycat mycat.c road@ubuntu:~/桌面/work$ ./mycat

usage : ./mycat filename

road@ubuntu:~/桌面/work$ ./mycat a

iamroad

road@ubuntu:~/桌面/work$

其中,a为一个文件名。

3.1用流文件系统函数重新编写上面的程序。

实验流程图:

不为3,提示

用流文件写的文件复制功能函数:

//fcp.c

#include

#include

#include

#include

int main(int argc,char * argv[])

{

FILE *fd1,*fd2;

char buffer[20];

if(argc!=3)

{

printf("argument error\n");

printf("usage : %s filename1 filename2\n",argv[0]);

return 1;

}

fd1=fopen(argv[1],"r");

if(fd1==NULL)

{

printf("file %s can not opened\n",argv[1]);

return 1;

}

fd2=fopen(argv[2],"w");

if(fd2==-1)

{

printf("Can not open file %s\n",argv[2]);

return 1;

}

while(!feof(fd1))

{

fread(&buffer,sizeof(char),1,fd1);

fwrite(&buffer,sizeof(char),1,fd2);

}

fclose(fd1);

相关文档
最新文档