文件和目录相关实验(三)

时间:2021-06-01 12:24:15

1. 题目

题目一

Write a utility like cp(1) that copies a file containing holes, without writing the bytes of 0 to the output file.

题目二

确定open函数是否增加link count数

2. 代码分析

2.1 题目一

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <err.h>
#define NUMBER 1
#define handle_error(msg) \
do { perror(msg); exit(EXIT_FAILURE); } while (0)

int main(int argc,char ** argv)
{
int num,fd[2];
char buf;
if(argc !=3)
errx(1,"usage filename1 filename2");
if(( fd[0] = open(argv[1],O_RDWR)) < 0)
handle_error("open");
if(( fd[1] = open(argv[2],O_RDWR|O_CREAT|O_TRUNC,S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH)) < 0)
handle_error("open");
while((num = read(fd[0],&buf,NUMBER)) > 0)
{
if(buf == 0)
{
if (lseek(fd[1],1, SEEK_CUR) == -1)
handle_error("lseek");
}
else
if(write(fd[1],&buf,num) == -1)
handle_error("write");
}
if(num == 0)
{
handle_error("read end of file");
}
else
handle_error("read");

}

  结果如下:

[root@localhost ~]# ./4_1 file.hole data3.txt
read end of file: Success
[root@localhost ~]# ll -s file.hole data3.txt
8 -rw-r--r--. 1 root root 16394 Jan 27 19:33 data3.txt
8 -rw-r--r--. 1 root root 16394 Jan 27 19:14 file.hole
[root@localhost ~]# od -c file.hole
0000000 a b c d e f g h i j \0 \0 \0 \0 \0 \0
0000020 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0
*
0040000 A B C D E F G H I J
0040012
[root@localhost ~]# od -c data3.txt
0000000 a b c d e f g h i j \0 \0 \0 \0 \0 \0
0000020 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0
*
0040000 A B C D E F G H I J
0040012

  此程序设计的时候非常担心if(buf == 0)是否能够按照预期工作,但是实际上确实实现了功能。但是实现效率就惨不忍睹了,使用STANDARD I/O来实现该程序将获得较高的效率。

2.2 题目二

#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <err.h>
#define handle_error(msg) \
do { perror(msg); exit(EXIT_FAILURE); } while (0)
struct stat buf;

int main(int argc,char ** argv)
{
int fd;
if(argc !=2)
errx(1,"usage filename1");
if(stat(argv[1],&buf) == -1)
handle_error("stat");
printf("link count before open: %d\n",buf.st_nlink);

if(( fd = open(argv[1],O_RDWR)) < 0)
handle_error("open");
if(stat(argv[1],&buf) == -1)
handle_error("stat");
printf("link count after open: %d\n",buf.st_nlink);

}

  结果如下:

[root@localhost ~]# ./4_2 data3.txt 
link count before open: 1
link count after open: 1
[root@localhost ~]#

  也就是说open并没有增加link count