创建文件Create_file_with_hole.c,内容为
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "apue.h"
char buf1[] = "abcdefghij";
char buf2[] = "ABCDEFGHIJ";
int
main(void) {
int fd;
if ( (fd = creat("file.hole", FILE_MODE)) < 0)
err_sys("creat error");
if (write(fd, buf1, 10) != 10)
err_sys("buf1 write error");
/* offset now = 10 */
if (lseek(fd, 40, SEEK_SET) == -1)
err_sys("lseek error");
/* offset now = 40 */
if (write(fd, buf2, 10) != 10)
err_sys("buf2 write error");
/* offset now = 50 */
exit(0);
}
- 编译
gcc Create_file_with_hole.c -o Create_file_with_hole -lapue
- 执行
./Create_file_with_hole
//od命令用来观察该文件的实际内容,-c表示以字符方式打印文件内容
od -c file.hole
编译,执行结果为
本文介绍了一个使用C语言创建带有空洞的文件的方法。通过示例代码展示了如何利用`creat`、`lseek`和`write`等系统调用创建一个包含特定数据段但中间存在空洞的文件,并给出了具体的编译及执行步骤。
739

被折叠的 条评论
为什么被折叠?



