理解概念:对于内核而言,所有打开文件都由文件描述符引用。
文件描述符是一个非负整数。
当当开一个现存的文件或者创造一个新文件时,内核向进程返回一个文件描述符。
当读,写一个文件是,用open或creat返回的文件描述符标识文件,将其作为参数送给read或write
1,学到unix设计中I/O的一些基本函数,open,read,write,lseek等;
2,学习了数字描述符的概念和应用;
3,初步了解空洞文件的概念;
4,为什么要调用出错函数的一点点原因;
说明非负整数文件描述符的一个小程序:(网络出处:unix高级编程)
#include
#include
#include
#include "wohdr.h"
char buf1[]="abcdefghij";
char buf2[]="ABCDEFGHIJ";
int
main(void){
int fd;
if( ( fd=creat("file.hole",FILE_MODE ) )<0)
printf("creat error");
if (write(fd,buf1,10)!=10){
printf("buf1 write error");
}
if (lseek(fd,40,SEEK_SET)==-1){
printf("lseek error");
}
if (write(fd,buf2,10)!=10){
printf("buf2 write error");
}
exit(0);
}
注意:其中的wohdr.h是自己定义的头文件
一个即能说明空洞文件,又能说明open,read,write的程序
from:google寻找空洞文件
#define RFILE "foo"
#define WFILE "bar"
#define BUFSIZ 8096
#define MODE 0644
#include
#include
#include
#include
#include
#include
int main(void)
{
int rfd, wfd, n;
struct stat rstat;
char buf[BUFSIZ];
if ((rfd = open(RFILE, O_RDONLY)) < 0) {
perror("open error");
exit(1);
}
/* Create the sparse file with the same size of RFILE */
if ((wfd = creat(WFILE, MODE)) < 0) {
perror("creat error");
exit(1);
}
if (fstat(rfd, &rstat) < 0) {
perror("fstat error");
exit(1);
}
if (lseek(wfd, rstat.st_size - 1, SEEK_SET) < 0) {
perror("lseek error");
exit(1);
}
if (write(wfd, "", 1) != 1) {
perror("write error");
exit(1);
}
/* Now copy RFILE to WFILE; nothing special */
if (lseek(wfd, 0, SEEK_SET) < 0) {
perror("lseek error");
exit(1);
}
while ((n = read(rfd, buf, BUFSIZ)) > 0) {
if (write(wfd, buf, n) != n) {
perror("write error");
exit(1);
}
}
if (n < 0) {
perror("read error");
exit(1);
}
return 0;
}
空洞文件的网络解释
from:http://www.linuxforum.net/forum/gshowflat.php?Cat=&Board=program&Number=351126&page=2&view=collapsed&sb=3&o=all&fpart=
The issue of 'holes' in files is thus:
Suppose a program creates a new file, seeks to a large offset, and then
writes 1 byte.
The file now consumes only 1 block of disk space, but appears to be large
(both in the byte size returned by stat(), and to a program that reads it
sequentially). The space that was never written to reads back as all
zeros, but consumes no space. This is referred to as a 'sparse file'.
The most common situation that causes these is use of the dbm package,
which takes advantage of this ability.
by hopesfish@2004-09-03