文件描述符
1.open functions
int open(const char *path, int oflag, ... /* mode_t mode */ );
#include "apue.h"
#include <fcntl.h>
int main(void)
{
int descriptors;
if((descriptors = open("/l22.c",O_RDWR | O_CREAT | O_TRUNC)) < 0)
printf("error");
else {
printf("ok");
close(descriptors);
}
}
2.creat function
3.close function
4.sleek function
若..............是SEEK_END,則...................................爲文件長度加offset
注:offset位移量可爲負數,比較返回值是應測試是否爲-1。
如果文件描述符引用的是一個管道(pipe)或FIFO,則lseek返回-1,並將errno設置爲EPIPE。
$ cat < /etc/passwd | ./a.out '|'爲管道符
$ ./a.out < /var/spool/cron/FIFO
/*
* function: Create a file with a hole in it
*/
#include "apue.h"
#include <fcntl.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, 16384, SEEK_SET) == -1)
err_sys("lseek error");
/* offset now = 16384 */
if(write(fd, buf2, 10) != 10)
err_sys("buf2 write error");
/* offset now = 16394 */
exit(0);
}
執行後的結果:
~/桌面/apue.3e/test/fileio$ 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