Linux系統編程:簡單檔案IO操作
一、 檔案描述符:
(1) 檔案描述符其實實質上是一個數字,這個數字在一個行程中表示一個特定的含義,當我們open打開一個檔案時,作業系統在記憶體中構建了一些資料結構來表示這個動態檔案,然后回傳給應用程式一個數字作為檔案描述符,這個數字就和我們記憶體中維護整個動態檔案的這些資料結構掛鉤系結上了,以后我們的應用程式如果需要操作整個動態檔案,只需要用整個檔案描述符進行區分。
(2) 按照慣例,UNIX系統shell把檔案描述符0與行程的標準輸入關聯,檔案描述符1與標準輸出關聯,檔案描述符2與標準錯誤關聯。在符合POSIX.1的應用程式中,幻數0、1、2雖然已經被標準化,但應當把他們替換成符號常量STDIN_FILENO、STDOUT_FILENO、STDERR_FILENO以提高可讀性。這些常數定義在<unistd.h>檔案中。
(3) 檔案描述符就是用來區分一個程式打開的多個檔案。
(4) 檔案描述符的作用域就是當前行程,出了當前行程整個檔案描述符就沒有意義了。
(5) Open回傳的fd必須記錄好,以后向整個檔案的所有操作都要靠整個fd去對應這個檔案,最后關閉檔案時也需要fd去指定關閉這個檔案,如果我們關閉檔案前fd丟了,那么這個檔案就沒法關閉了也沒法去讀寫了。
二、 什么是I/O
1、 輸入/輸出是主存和外部設備之間拷貝資料的程序
(1) 設備->記憶體 (輸入操作)
(2) 記憶體->設備(輸出操作)
2、 對linux來說,有2種型別的I/O:
(1) ANSIC提供的標準I/O庫稱為高級I/O,通常也稱為帶緩沖的I/O
(2) 低級I/O,通常也稱為不帶緩沖的I/O
三、檔案IO相關頭檔案:
一般頭檔案在/usr/include下面,這里是標準C程式頭檔案,如果你的頭檔案前面加了<sys/*>那說明這是系統呼叫函式頭檔案,其在/usr/include/sys下面。
#include <unistd.h>
符號常量是POSIX標準定義的unix系統定義符號常量的頭檔案,包含了許多UINX系統服務的函式原型,例如read函式write函式和getpid函式。
#include <fcntl.h>
fcntl.h,是unix標準的通用頭檔案,其中包含了相關函式有open,fcntl,shutdown,unlink,fclose等
#include <sys/types.h>
基本系統資料型別,是UINX/LINUX系統的基本資料型別的頭檔案,含size_t,time_t,pid_t等型別。
#include <sys/stat.h>
檔案狀態,是Uinx/linx系統定義的檔案狀態所在的偽標準頭檔案含有以下型別:
dev_t st_dev Device ID of device containing file.
ino_t st_ino File serial number.
mode_t st_mode Mode of file (see below).
nlink_t st_nlink Number of hard links to the file.
uid_t st_uid User ID of file.
gid_t st_gid Group ID of file.
dev_t st_rdev Device ID (if file is character or block special).
off_t st_size For regular files, the file size in bytes.
For symbolic links, the length in bytes of the
pathname contained in the symbolic link.
For a shared memory object, the length in bytes.
For a typed memory object, the length in bytes.
For other file types, the use of this field is
unspecified.
time_t st_atime Time of last access.
time_t st_mtime Time of last data modification.
time_t st_ctime Time of last status change.
int chmod(const char *, mode_t);
int fchmod(int, mode_t);
int fstat(int, struct stat *);
int lstat(const char *restrict, struct stat *restrict);
int mkdir(const char *, mode_t);
int mkfifo(const char *, mode_t);
int mknod(const char *, mode_t, dev_t);
int stat(const char *restrict, struct stat *restrict);
mode_t umask(mode_t);
使用stat函式最多的可能是ls –l命令,用其可以獲得有關一個檔案的所有資訊.
#include <errno.h>
在系統編程中錯誤通常通過函式回傳值雷表示,并通過特殊變數errno來描述。
在errno這個全域變數在<errno.h>頭檔案中宣告如下:
exitern int errno
錯誤處理函式
perror
strerror
四、檔案描述符與檔案指標相互轉換
對于系統呼叫中的檔案描述符與ANSI C標準中的檔案指標可以通過以下函式進行轉換:
1、 fileno:將檔案指標轉換成檔案描述符
2、 fdopen:將檔案描述符轉換為檔案指標
五、檔案系統呼叫
1、open系統呼叫
(1)有幾種方法可以獲得允許訪問檔案的檔案描述符,最常用的是使用open()系統呼叫。
2、函式原型
Int open(const char *path, int flags);
引數
Path: 檔案的名稱,也可以包含(絕對和相對)路徑
Flags: 檔案的打開模式
回傳值
打開成功,回傳檔案描述符;非負整數
打開失敗,回傳-1
六、
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/20937.html
標籤:應用程序開發區
下一篇:安裝ubuntu后啟動不了
