linux下的七種文件
- 文件
d 目錄
l 符號鏈接
s 套接字
b 塊設備
c 字符設備
p 管道
僞文件是不佔用磁盤空間的
常用的系統調用 umask
1.文件權限問題
如果open 給定一個文件權限 與 umask掩碼 運算之後在賦予權限
當然 你也可以修改umask掩碼 一個簡單的demo
這個api非常簡單 我們這裏就不做演示了
來討論一下lseek函數
1.這個函數是用來設置文件的文件指針位置的 大家都知道 一個文件只有一個文件指針,當你去寫入一段數據之後,如果不重新設置一下文件的偏移,你在讀的話 文件指針已經到了文件的末尾了,所以你是讀不到數據的
2.這個函數還有第二個作用用來實現文件的拓展(不過在拓展之後要進行一次寫的操作纔行)
#include <iostream>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <sys/stat.h>
using namespace std;
int32_t
main(int argc, char* argv[])
{
int32_t fd = open("./tmp", O_RDWR | O_CREAT | O_EXCL, 0644);
if (fd < 0) {
fprintf(stderr, "create file error the reason is %s\n", strerror(errno));
exit(1);
}
int ret = lseek(fd, 0, SEEK_SET);
printf("current offset location is %d\n", ret);
// 設置文件擴展
ret = lseek(fd, 200, SEEK_END);
printf("current offset location is %d\n", ret);
// 進行一次操作
write(fd, "a", 1);
close(fd);
return 0;
}
效果如下:
我們來打開這個創建的文件來看看情況
看 a 就是在後面 先來介紹一個這個^@ 這個符號稱爲空洞符號,也許大家會感到陌生但是 如果你下載過小電影就知道
其實你下載的數據還沒有收到 系統就已經在磁盤上創建了一個和你想要下載的文件同樣大小的文件裏面就是空洞符號,爲什麼要這樣呢,因爲你如果一遍下載一遍擴容的話,這樣IO的處理效率就非常的底下,所以預先分配一塊空間 你來了就往裏面IO就行了
第二種擴容凡是 ftrucate / trucate
兩者其實差不過 就是根據不同的方式操作而已 ,相比lseek 擴容之後是不用在進行一次寫操作的
我們來通過一個簡單的demo認識一下他吧 把上面的代碼改動一下 吧lseek的部分註釋掉,在創建一個tmp1的文件對它進行擴容
#include <iostream>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <sys/stat.h>
using namespace std;
int32_t
main(int argc, char* argv[])
{
int32_t fd = open("./tmp1", O_RDWR | O_CREAT | O_EXCL, 0644);
if (fd < 0) {
fprintf(stderr, "create file error the reason is %s\n", strerror(errno));
exit(1);
}
int ret = 0;
#if 0
ret = lseek(fd, 0, SEEK_SET);
printf("current offset location is %d\n", ret);
// 設置文件擴展
ret = lseek(fd, 200, SEEK_END);
printf("current offset location is %d\n", ret);
// 進行一次操作
write(fd, "a", 1);
#else
ret = ftruncate(fd, 300);
if (ret < 0) {
fprintf(stderr, "exten file error the reason is %s\n", strerror(errno));
}
#endif
close(fd);
return 0;
}
來看看tmp1:
其實這兩個函數用起來都是非常簡單的,後續的我會給大家介紹更多的 linux文件操作 ,目錄操作, 進程相關(IPC爲代表的),線程相關(同步異步之類爲代表的)
網絡相關(如多路io轉接服務器,TCP的介紹),框架相關(Libevent Libco(協程相關))
這裏的話主要是給大家一個步入linuxC/C++開發的心裏準備
更多的C/C++ linux編程我會在下面的文章中陸續的分享,也可以關注‘奇牛學院’
來一起討論