linux-io
# C库函数
fopen/fclose/fread/fwrite/fgets/fputs/fscanf/fprintf/fsseek/fgetc/fputc/fteel/feof/fflush FILE* fp; 文件描述符 - 索引到对应的磁盘文件 文件读写指针位置 - 读写文件过程中指针的实际位置 IO缓冲区 - 通过寻址找到对应内存块,数据从内存写到磁盘
# 虚拟地址空间
Linux每一个运行的程序(进程),操作系统都会为其分配一个0~4G的地址空间(虚拟地址空间) 4G PCB进程控制块 -> 文件描述符表[] -> 文件描述符 宏定义 内存管理 | 0 STDIN_FILENO 内 进程管理 -- 1 STDOUT_FILENO 核 设备驱动管理 2 STDERR_FILENO 区 VFS虚拟文件系统 3 ... 1023 3G 环境标量(env) 用 命令行参数 户 栈空间 < 区 共享库:C标准库、Linux系统IO函数 堆空间 >/^ .bss(未初始化的全局变量) | .data(已初始化的全局变量) |———— Linux下可执行文件的格式:ELF .rodata: 只读数据段 | .text(代码段,二进制机器指令) | 0 受保护的地址(0~4k)
cpu为什么要使用虚拟地址空间与物理地址空间映射?解决了什么问题?
- 方便编译器和操作系统安排程序的地址分布。 程序可以使用一系列相邻的虚拟地址来访问物理内存中不相邻的大内存缓冲区。
- 方便进程之间的隔离 不同进程使用的虚拟地址彼此隔离,一个进程中的代码无法更改正在由另一进程使用的物理内存。
- 方便OS使用你那可怜的内存。 程序可以使用一系列虚拟地址来访问大于可用物理内存的内存缓冲区
# 系统IO函数
# open
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main()
{
// 打开一个已经存在的文件
int fd = open("english.txt", O_RDONLY);
if(fd == -1)
{
perror("open fail");
exit(1);
}
// 创建一个新文件
int fd1 = open("newfile", O_CREAT | O_WRONLY, o664);
if(fd1 == -1)
{
perror("open1 fail");
exit(1);
}
//read file
char buf[2014] = {0};
int count = read(fd, buf, sizeof(buf));
if(count == -1)
{
perror("read fail");
exit(1);
}
while(count)
{
// 将读出的数据写入另一个文件中
int ret = write(fd1, buf, count);
count = read(fd, buf, sizeof(buf));
}
// close file
close(fd);
close(fd1);
}
# lseek
- 获取文件大小 int ret = lseek(fp, 0, SEEK_END);
- 移动文件指针
- 文件拓展 int ret = lseek(fp, 2000, SEEK_END); // 实现文件拓展,需要在最后做一次写操作 单lseek是不能进行拓展的 write(fd, "a", 1);
# 文件操作相关系统函数
# stat 获取文件相关信息
也是命令 stat file 查看file文件信息
struct stat{
dev_t st_dev; //文件的设备编号
ino_t st_ino; //节点
mode_t st_mode; //文件的类型和存取的权限 2byte ____???rwxrwxrwx
nlink_t st_nlink; //连到该文件的硬链接数目
uid_t st_uid; //用户id
gid_t st_gid; //组id
dev_t st_rdev; //(设备类型)若此文件为设备文件,则为其设备编号
off_t st_size; //文件字节数
blksize_t st_blksize; //块大小
blkcnt_t st_blocks; //块数
time_t st_atime; //最后一次访问时间
time_t st_mtime; //最后一次修改时间
time_t st_ctime; //最后一次改变时间(指属性)
}
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int stat(const char *path, struct stat *buf);
# access函数
测试指定文件是否存在/拥有某种权限。
# chmod函数
修改文件的访问权限 int chmod(const char *path, mode_t mode); 成功:0;失败:-1设置errno为相应值 int fchmod(int fd, mode_t mode);