1 fd是個啥
(1)linux中的文件描述符fd的合法范圍是0或者一個正正數,不可能是一個負數。
(2)open返回的fd程序必須記錄好,以后向這個文件的所有操作都要靠這個fd去對應這個文件,最后關閉文件時也需要fd去指定關閉這個文件。如果在我們關閉文件前fd丟掉了那就慘了,這個文件沒法關閉了也沒法讀寫了。
2 學會實時查man手冊
(1)當我們寫應用程序時,很多API原型都不可能記得,所以要實時查詢,用man手冊
(2)man 1 xx查linux shell命令,man 2 xxx查API, man 3 xxx查庫函數
3 讀取文件內容
(1)ssize_t read(int fd, void *buf, size_t count);
fd表示要讀取哪個文件,fd一般由前面的open返回得到 buf是應用程序自己提供的一段內存緩沖區,用來存儲讀出的內容 ,count是我們要讀取的字節數 返回值size_t類型是linux內核用typedef重定義的一個類型(其實就是int),返回值表示成功讀取的字節數。
4 向文件中寫入
(1)寫入用write系統調用,write的原型和理解方法和read相似
(2)注意buf的指針類型為void
(3)剛才先寫入12字節,然后讀出結果讀出是0(但是讀出成功了)。
1 #include <stdio.h> 2 #include <sys/types.h> 3 #include <sys/stat.h> 4 #include <fcntl.h> 5 #include <unistd.h> 6 #include <string.h> 7 8 9 10 int main(int argc, char *argv[]) 11 { 12 int fd = -1; // fd 就是file descriptor,文件描述符 13 char buf[100] = {0}; 14 char writebuf[20] = "l love linux"; 15 int ret = -1; 16 17 // 第一步:打開文件 18 fd = open("a.txt", O_RDWR);//注意之前自己定義個a.txt 19 if (-1 == fd) // 有時候也寫成: (fd < 0) 20 { 21 printf("文件打開錯誤\n"); 22 } 23 else 24 { 25 printf("文件打開成功,fd = %d.\n", fd); 26 } 27 28 // 第二步:讀寫文件 29 // 寫文件 30 ret = write(fd, writebuf, strlen(writebuf)); 31 if (ret < 0) 32 { 33 printf("write失敗.\n"); 34 } 35 else 36 { 37 printf("write成功,寫入了%d個字符\n", ret); 38 } 39 /* 40 // 讀文件 41 ret = read(fd, buf, 5); 42 if (ret < 0) 43 { 44 printf("read失敗\n"); 45 } 46 else 47 { 48 printf("實際讀取了%d字節.\n", ret); 49 printf("文件內容是:[%s].\n", buf); 50 } 51 */ 52 // 第三步:關閉文件 53 close(fd); 54 55 return 0; 56 }