一、文件IO的概述
 1、什么是文件?
 Linux下一切皆文件。普通文件、目录文件、管道文件、套接字文件、链接文件、字符设备文件、块设备文件。
 2、什么是IO?
 input  output:输入输出
 3、什么是文件IO?
 对文件的输入输出,把数据写入文件/从文件中读取数据
 系统IO:系统调用的IO接口。(open、close、read、write、lseek、mmap、munmap)
 标准IO:基于标准C库的IO接口
 二、系统IO函数的应用
 Linux下的man手册的使用:man  man
 第一节:查可执行程序:man 1 ls
 第二节:查系统调用的函数:man 2 open
 第三节:查库调用的函数:man 3 printf- 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); 返回值类型:int
 返回值:
         打开文件成功,返回一个新的文件描述符,>=0(相当于人的身份证号)
         打开文件失败,返回-1
 形参:
         pathname:要打开的文件的路径名
         flags:打卡文件的方式
         O_RDONLY  只读
         O_WRONLY 只写
         O_RDWR     可读可写
         以上三种方式互斥
         O_APPEND:以追加方式打开文件。
         O_CREAT:如果要打开的文件不存在,系统就创建该文件并打开。
         O_TRUNC:如果要打开的文件中已有数据,那就打开文件并清除已有的数据。
 mode:用于指定新建文件的权限,用八进制表示。
- close 关闭文件函数
 #include <unistd.h>   
 int close(int fd);
 返回值类型:int
 返回值:
        关闭文件成功,返回0
        关闭文件失败,返回-1
 形参
        fd:要关闭的文件的文件描述符
练习:编写代码,实现在共享目录中,打开1.txt文件,并打印出文件描述符,再关闭文件。
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
int main()
{
    //打开文件
    int fd1;
    fd1 = open("./1.txt",O_RDWR);
    if(fd1 == -1)
    {
        printf("open 1.txt failed!\n");
        return -1;
    }
    printf("fd1 = %d\n",fd1);
    close(fd1);
    return 0;
}
/*
fd1 = 3;
文件描述符是从3开始的,为什么会这样?不是说文件描述符>=0?
其实系统会默认打开三个标准流控,0,1,2就会被占用
0 ---> 标准输入   stdin
1 ---> 标准输出   stdout
2 ---> 标准错误   stderr
所以当我们自己用open函数打开文件时,文件描述符是从3开始的
*/
 - lseek   偏移文件指针
 #include <sys/types.h>
 #include <unistd.h>
 
 off_t lseek(int fd, off_t offset, int whence); 返回值类型:off_t (整形)
 返回值:
          偏移成功,返回偏移字节数
          偏移失败,返回-1
 形参一:fd  文件描述符
 形参二:偏移量
 形参三:偏移位置
          SEEK_SET   从头位置开始偏移
          SEEK_CUR  从当前位置开始偏移
          SEEK_END  从末尾位置开始偏移
 练习2:编写代码,实现在1.txt文件中写入"hello world",再从该文件中读取5个字节数据,并打印出来。
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
int main(void)
{
    //1.打开文件
    int fd = open("./1.txt", O_RDWR|O_CREAT);
   
    if (fd == -1)
    {
        printf("open  1.txt failed!\n");
        return -1;
    }
    //2.写入数据
    char wr_buf[15] = "hello world";
    write(fd, wr_buf, 11);    
    //3.读取数据
    char rd_buf[15] = {0};
    lseek(fd, 0, SEEK_SET);
    read(fd, rd_buf,5);
    
    printf("%s\n", rd_buf);
    
    //4.关闭文件
    close(fd);
   
    return 0;
}作业:实现一个简单文件拷贝功能,将文件1的数据拷贝到文件2,如果文件2不存在则创建,如果文件2中已有数据则清除。



















