基础IO

系统文件IO
操作文件除了c接口,我们还可以采用系统接口来进行文件访问。
hello.c写文件:

#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>

int main()
{
    int fd = open("file",O_WRONLY|O_CREAT,0644);//以只写方式打开或不存在的话创建
    if(fd < 0)
    {
        perror("open");
        return 1;//程序失败
    }
    const char* msg = "hello world!\n";
    int count = 5;
    while(count--)//往文件里写5条程序
    {
        write(fd,msg,strlen(msg));
    }
    close(fd);//关闭文件
    return 0;
}

hello.c读文件:

#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>

int main()
{
    int fd = open("file",O_WRONLY|O_CREAT,0644);//以只写方式打开或不存在的话创建
    if(fd < 0)
    {
        perror("open");
        return 1;//程序失败
    }
    const char* msg = "hello world!\n";
    int count = 5;
    while(count--)//往显示器上写5条程序
    {
        write(1,msg,strlen(msg));
    }
    close(fd);//关闭文件
    return 0;
}

文件描述符fd:通过对open函数的学习,我们知道了文件描述符就是一个小整数
FILE
因为IO相关函数与系统调用接口对应,并且库函数封装系统调用,所以本质上,访问文件都是通过fd访问的。
所以C库当中的FILE结构体内部,必定封装了fd。

#include <stdio.h>
#include <string.h>
int main()
{
const char *msg0="hello printf\n";
const char *msg1="hello fwrite\n";
const char *msg2="hello write\n";
printf("%s", msg0);
fwrite(msg1, strlen(msg0), 1, stdout);
write(1, msg2, strlen(msg2));
fork();
return 0;
}

运行出结果:

hello printf
hello fwrite
hello write

综上: printf fwrite 库函数会⾃自带缓冲区,⽽而 write 系统调⽤用没有带缓冲区。另外,我们这⾥里所说的缓冲区,都是⽤用户级缓冲区。其实为了提升整机性能,OS也会提供相关内核级缓冲区,不过不再我们讨论范围之内。
那这个缓冲区谁提供呢? printf fwrite 是库函数, write 是系统调⽤用,库函数在系统调⽤用的“上层”, 是对系统调⽤用的“封装”,但是 write 没有缓冲区,⽽而 printf fwrite 有,⾜足以说明,该缓冲区是⼆二次加上的,⼜又因为是C,所以由C标准库提供
硬链接:真正找到磁盘上文件的并不是文件名,而是inode。其实在linux中可以让多个文件名对应于同一个inode。

这里写图片描述

  1. abc和def的链接状态完全相同,他们被称为指向文件的硬链接。内核记录了这个连接数,innode 37117133的硬连接数为2
  2. 我们在删除文件时干了两件事:
    (1)在目录中将对应的记录删除
    (2)将硬连接数-1,如果为0,则对应的磁盘释放。

软连接:硬链接是通过inode引用另外一个文件,软连接是通过名字引用另外一个文件
动态库和静态库

  1. 静态库(.a):程序在编译链接的时候把库的代码链接到可执⾏行⽂文件中。程序运⾏行的时候将不再需要静态库
  2. 动态库(.so):程序在运⾏行的时候才去链接动态库的代码,多个程序共享使⽤用库的代码。
  3. 一个与动态库链接的可执行文件仅仅包含它用到的函数入口地址的一个表,而不是外部函数所在目标文件的整个机器码
  4. 在可在执行文件开始运动以前,外部函数的机器码由操作系统从磁盘上的该动态库中复制到内存中,这个过程称为动态链接。
  5. 动态库可以在多个程序间共享,所以动态链接是的可执行文件更小,节省了磁盘空间。操作系统采用虚拟内存机制允许物理内存中的一份动态库被要用到该库的所有进程共用,节省了内存和磁盘空间。

猜你喜欢

转载自blog.csdn.net/zhangjie1315/article/details/80149645