apue file i/o 學習筆記

文件描述符

  對於內核而言,所有打開文件都由文件描述符引用。當打開一個現存文件或創建一個新文件時,內核向進程返回一個文件描述符。當讀、寫一個文件時,用open或creat返回的文件描述符標識該文件,將其作爲參數傳送給read 或write。
  STDIN_FILENO       0   標準輸入     被定義在<unistd.h>
  STDOUT_FILENO   1   標準輸出
  STDERR_FILENO   2   標準出錯輸出


1.open functions

    int open(const char *path, int oflag, ... /* mode_t mode */ );

   oflag  argument:
             O_RDONLY         Open for reading only.
             O_WRONLY        Open for writing only
             O_RDWR             Open for reading and writing
             在這個三個常數中應當指定一個。
             O_EXEC              Open for execute only          這個沒有定義,不知道爲何
             O_SEARCH         Open for search only
             上面五個常數一定要指定一個,下面的可選擇:
             O_APPEND         Append to the end of file on each write 
             O_CLOEXEC      Set the FD_CLOEXEC file descriptor flag
             O_CREAT           Create the file if it doesn't exist 
             O_DIRECTORY  Generate an error if path doesn’t refer to a directory.
             O_EXCL             Generate an error if O_CREAT is also specified and the file already  exists.

        
  
#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 

     #include <fcnt1.h>
     int creat(const char  *path,  mode_t mode);
     等價於 open(path, O_WRONLY | O_CREAT | O_TRUNC, mode);

3.close function 

    #include <unistd.h>
    int close(int fd);

4.sleek function

     #include <unistd.h>
     off_t lseek(int fd, off_t offset, int whence);       //返回:若成功爲新的文件位移,若出錯爲-1
 
     若whence 是SEEK_SET,則將該文件的位移量設置爲距文件開始處offset個字節
     若..............是SEEK_CUR,則...................................爲其當前值加offset

     若..............是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









發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章