实验四L i n u x下的C语言编程
四、实验内容
本实验要求在 LINUX/UNIX 环境下用 C 语言编写三个具体的 SHELL 命令,基
本涉及了 LINUX/UNIX 文件系统中较为常用的有关文件操作的系统调用。内容如
下:
1、编程实现 copy 命令。执行格式:copy file1file2file3
功能:将 file1、file2 两文件的内容合并拷入 file3 中,其中间应有 30
个字节的空洞(调试成功后可将空洞调大到几十MB)。
程序执行后用 du 命令显示其占用磁盘空间,观察其大小,分析原因。程序可能
涉及到的系统调用: read(), write(), open(), creat(),
close(), lseek()
#include
#include
#include <>
#include <>
#include <>
#include <>
#include <>
int main(int argc, char const *argv[])
{
int file1,file2,file3;
if (argc!= 4) {
printf("Usage: copy file1 file2 file3\n");
exit(1);
}
file1=open(argv[1],O_RDONLY);
file2=open(argv[2],O_RDONLY);
file3=open(argv[3],O_CREAT|O_RDWR,S_IRWXU);
int n;
char buf[1024];
while (( n=read(file1,buf,1024))>0)
if (write(file3,buf,n)!=n)
printf("write error\n");
if (n<0)
printf("read %s error\nErrno= %d\n",argv[1],errno);
if (lseek(file3,30,SEEK_END)==-1)
printf("lseek error ");
while (( n=read(file2,buf,1024))>0)
if (write(file3,buf,n)!=n)
printf("write error\n");
if (n<0)