文件IO引入
文章目錄
- 1 文件從哪里來
- 2 怎么訪問文件
- 2.1 通用的IO模型
- 2.2 不是通用的函數(shù)
- 3 系統(tǒng)調(diào)用怎么進(jìn)入內(nèi)核
- 在這里插入圖片描述
- 4 內(nèi)核的sys_open、sys_read會做什么
1 文件從哪里來
在Linux系統(tǒng)中,一切都是“文件”:普通文件、驅(qū)動程序、網(wǎng)絡(luò)通信等等。所有的操作,都是通過“文件IO”來操作的。所以,很有必要掌握文件操作的常用接口。
文件一般從如下來:
2 怎么訪問文件
2.1 通用的IO模型
通用的IO模型有:open/read/write/lseek/close。示例代碼如下:
#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <stdio.h>/** ./copy 1.txt 2.txt* argc = 3* argv[0] = "./copy"* argv[1] = "1.txt"* argv[2] = "2.txt"*/ int main(int argc, char **argv) {int fd_old, fd_new;char buf[1024];int len;/* 1. 判斷參數(shù) */if (argc != 3) {printf("Usage: %s <old-file> <new-file>\n", argv[0]);return -1;}/* 2. 打開老文件 */fd_old = open(argv[1], O_RDONLY);if (fd_old == -1){printf("can not open file %s\n", argv[1]);return -1;}/* 3. 創(chuàng)建新文件 */fd_new = open(argv[2], O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);if (fd_new == -1){printf("can not creat file %s\n", argv[2]);return -1;}/* 4. 循環(huán): 讀老文件-寫新文件 */while ((len = read(fd_old, buf, 1024)) > 0){if (write(fd_new, buf, len) != len){printf("can not write %s\n", argv[2]);return -1;}}/* 5. 關(guān)閉文件 */close(fd_old);close(fd_new);return 0; }2.2 不是通用的函數(shù)
有些函數(shù)不是通用的函數(shù):ioctl/mmap。示例代碼如下:
#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <stdio.h> #include <sys/mman.h>/** ./copy 1.txt 2.txt* argc = 3* argv[0] = "./copy"* argv[1] = "1.txt"* argv[2] = "2.txt"*/ int main(int argc, char **argv) {int fd_old, fd_new;struct stat stat;char *buf;/* 1. 判斷參數(shù) */if (argc != 3) {printf("Usage: %s <old-file> <new-file>\n", argv[0]);return -1;}/* 2. 打開老文件 */fd_old = open(argv[1], O_RDONLY);if (fd_old == -1){printf("can not open file %s\n", argv[1]);return -1;}/* 3. 確定老文件的大小 */if (fstat(fd_old, &stat) == -1){printf("can not get stat of file %s\n", argv[1]);return -1;}/* 4. 映射老文件 */buf = mmap(NULL, stat.st_size, PROT_READ, MAP_SHARED, fd_old, 0);if (buf == MAP_FAILED){printf("can not mmap file %s\n", argv[1]);return -1;}/* 5. 創(chuàng)建新文件 */fd_new = open(argv[2], O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);if (fd_new == -1){printf("can not creat file %s\n", argv[2]);return -1;}/* 6. 寫新文件 */if (write(fd_new, buf, stat.st_size) != stat.st_size){printf("can not write %s\n", argv[2]);return -1;}/* 7. 關(guān)閉文件 */close(fd_old);close(fd_new);return 0; }3 系統(tǒng)調(diào)用怎么進(jìn)入內(nèi)核
4 內(nèi)核的sys_open、sys_read會做什么
參考資料:
總結(jié)
- 上一篇: 信用卡的积分会过期吗 大部分会有时间限
- 下一篇: man、info、help