对文件I/O的基本认识

一、文件I/O函数
常见的文件I/O函数有 open()、close()、read()、write()、lseek();

open()函数

函数功能:打开一个文件
包含的头文件:
       #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); 
参数:
    pathname:文件的路径;
    flags:O_RDONLY 只读打开;
           O_WRONLY 只写打开
           O_RDWR 读、写打开
           O_CREAT 若文件不存在时,则创建。需要用mode指明权限
           O_APPEND  追加写
返回值:打开文件的文件描述符

当目标文件存在时,选用两个参数的open()函数;
当目标文件不存在时,需要open()创建,第三个参数代表创建文件的默认权限,故使用第二个open()函数。

close()函数

函数功能:将打开的文件关闭
头文件::
    #include <unistd.h>
函数原型:
    int close(int fd);

返回值:成功返回0;失败返回-1.
  1 #include<stdio.h>
  2 #include<sys/types.h>
  3 #include<sys/stat.h>
  4 #include<fcntl.h>
  5 #include <unistd.h>
  6 int main()
  7 {
  8     int fd = open("07test.c",O_RDONLY);
  9     if(fd < 0)
 10     {
 11         perror("open");
 12         exit(-1);
 13     }
 14     close(fd);
 15     return 0;
 16 }                                                                                                 

read()函数

函数功能:读文件的内容

函数原型;
    ssize_t read(int fd,const void *buf,size_t count);
参数:
    fd:打开的文件描述符;
    buf:读取的内容装到buf里;
    conut:这个地方的大小。
返回值:实际读取的字节个数

write()函数

函数功能:向文件里面写内容
函数原型:
    ssize_t write(int fd,const void *buf,size_t count);
    fd:打开的文件描述符;
    buf:写的内容在buf里存着;
    conut:这个地方的大小。
返回值:实际写的字节个数

lseek()函数

函数功能:移动文件的读写位置;

    #include <sys/types.h>
    #include <unistd.h>
函数原型:
    off_t lseek(int fd, off_t offset, int whence);
参数:
    whence:
        SEEK_SET:参数offset为新的读写位置;
        SEEK_CUR:从当前的读写位置往后增加offset的偏移量;
        SEEK_END:将读写位置指向文件末尾后再增加offset的偏移量
SEEK_CUR和SEEK_END允许出现负值。

二、文件描述符
Linux进程默认会打开三个文件描述符,分别是标准输入0、标准输出1、标准错误2;
文件描述符的本质是:数组的下标。
文件描述符的分配规则:

  1 #include<stdio.h>
  2 #include<sys/types.h>
  3 #include<sys/stat.h>
  4 #include<fcntl.h>
  5 
  6 int main()
  7 {
  8     int fd = open("myfile",O_RDONLY);
  9     if(fd < 0)
 10     {
 11         perror("open");
 12         return 1;
 13     }
 14     printf("fd:%d\n",fd);
 15     close(fd);
 16     return 0;
 17 }

程序运行结果是 fd:3
由此可见,文件描述符的分配规则是:
在file_struct数组中,找到当前没有被使用的最小的下标,作为新的文件描述符。

三、重定向

  1 #include<stdio.h>
  2 #include<sys/types.h>
  3 #include<sys/stat.h>
  4 #include<fcntl.h>
  5 #include<stdlib.h>
  6 
  7 int main()
  8 {
  9     close(1);
 10     int fd = open("myfile",O_RDONLY | O_CREAT,0644);
 11     if(fd < 0)
 12     {
 13         perror("open");
 14         return 1;
 15     }
 16     printf("fd:%d\n",fd);
 17     close(fd);
 18     return 0;
 19 }

程序运行结果:什么也没输出
原本应该输出到显示器上的内容,输出到了文件myfile中,其中fd = 1.这种现象称为重定向。常见的重定向有>、>>、<.

这里写图片描述
printf是C库当中的IO函数,一般往标准输出中写,但stdout底层访问文件的时候,找的还是fd:1,但此时,fd:1下标所表示的内容,已经是myfile的地址,故输出的任何消息都会写入myfile中,从而完成输出重定向。

猜你喜欢

转载自blog.csdn.net/weixin_41289858/article/details/81147633