#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> int open(const char *pathname, int flags); int open(const char *pathname, int flags, mode_t mode);
例子:模擬touch命令linux
#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> int main(int argc, char* argv[]){ int fd = open(argv[1], O_RDONLY|O_CREAT|O_EXCL, 0666); close(fd); return 0; }
0666 & ~0002 = 0664,因此建立出來的文件的權限是:-rw-rw-r--c++
#include <unistd.h> ssize_t read(int fd, void *buf, size_t count);
#include <unistd.h> ssize_t write(int fd, const void *buf, size_t count);
例子:模擬cat命令微信
#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> int main(int argc, char* argv[]){ int fd = open(argv[1], O_RDONLY); char buf[64] = {0}; int ret = 0; while((ret = read(fd, buf, sizeof buf)) > 0){ write(STDOUT_FILENO, buf, ret); } close(fd); return 0; }
#include <sys/types.h> #include <unistd.h> off_t lseek(int fd, off_t offset, int whence);
例子1:把字符串「helloworld」寫入一個文件,而後讀取這個文件,把「helloworld」從文件中讀取出來,並打印到終端。學習
#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> int main(int argc, char* argv[]){ int fd = open(argv[1], O_RDWR|O_CREAT, 0666); write(fd, "helloworld\n", 11); //這裏必須使用lseek,來調整文件指針的位置,設置文件指針設置到文件的開始位置。 lseek(fd, 0, SEEK_SET); char buf[20] = {0}; int ret = read(fd, buf, sizeof buf); write(STDOUT_FILENO, buf, ret); close(fd); return 0; }
例子2:計算文件的大小指針
#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdio.h> #include <unistd.h> int main(int argc, char* argv[]){ int fd = open(argv[1], O_RDWR); //open後,文件指針的位置在文件開頭 //由於:lseek返回當前位置到開始位置的長度 //因此用lseek移動到了文件末尾,這時lseek的返回值就是文件的大小 int ret = lseek(fd, 0, SEEK_END); printf("file size:%d\n", ret); close(fd); }
例子3:建立文件大小爲1024的文件code
#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdio.h> #include <unistd.h> int main(int argc, char* argv[]){ int fd = open(argv[1], O_WRONLY|O_CREAT, 0666); //打開後文件指針在文件的開始位置,而後從開始位置移動1023個字節,而後再調用write, //注意不調用後面的write的話,建立的文件的大小是爲0的。 lseek(fd, 1023, SEEK_SET); write(fd, "a", 1); close(fd); }