一、关于文件IO
文件IO遵循POSIX标准,文件IO实际上使用的系统调用函数
与标准IO的区别:
标准IO适用于操作普通文件
文件IO适用于任意类型文件
标准IO中通过流唯一标识一个文件
文件IO中通过文件描述符唯一标识一个文
二、文件描述符
文件描述符是一个按顺序分配的最小的非负整数,当用户打开或新建一个文件时,系统回向当前返回一个最小的可用的文件描述符。
三个特殊的文件描述符
标准输入 -- 0 -- stdin
标准输出 -- 1 --stdout
标准错误 -- 2 --stderr
三、文件相关系统调用函数
open、close --打开关闭文件
read、write -- 读写文件
lseek -- 文件定位
(1)打开、新建文件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:当打开文件不存在时,用该选项创建新文件,并用第三个参数为其设置权限
O_EXCL:一般和O_CREAT联合使用,用于检测文件是否存在
O_APPEND:以追加方式打开文件,在文件末尾另起一行继续写入
O_TRUNC:打开文件后,会将原文件清空
mode:
当需要创建新文件时,需要用该参数给新建文件设置权限0664
返回值:
成功返回文件描述符,失败返回-1;
(2)关闭文件 ——close
#include <unistd.h>int close(int fd);
参数:
fd:要关闭文件的文件描述
返回值:
成功返回0,失败返回-1
(3)读写文件
#include <unistd.h>ssize_t read(int fd, void *buf, size_t count);
参数:
fd:读取文件的文件描述符
buf:用户自定义的缓冲区,用于存放读取的内容
count:请求读取的字节数
返回值:
成功返回读取的字节数,失败返回-1,返回0标识读到文件末尾;#include <unistd.h>
ssize_t write(int fd, const void *buf, size_t count);
参数:
fd:写入文件的文件描述符
buf:用户自定义的缓冲区,用于存放准备写入的内容
count:请求写入的字节数
返回值:
成功返回读取的字节数,失败返回-1
练习:
用文件IO实现文件拷贝
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
int main(int argc, char *argv[])
{
int fp1 = open("1.text",O_RDONLY);
int fp2 = open("2.text",O_WRONLY | O_CREAT,0664);
if(fp1==-1 | fp2==-1)
{
perror("open");
return -1;
}
char buf[64]={0};
int ret;
while((ret=read(fp1,buf,10))>0)
{
write(fp2,buf,ret);
memset(buf,0,sizeof(buf));
}
return 0;
}
(4)文件定位 -- lseek()
#include <sys/types.h>
#include <unistd.h>off_t lseek(int fd, off_t offset, int whence);
参数:
fd:文件描述符
offset:偏移量,可正可负
whence:基准点
SEEK_SET:定位在文件开头
SEEK_CUR:定位在当前位置
SEEK_END:定位在文件末尾
返回值:
成功返回当前定位位置相对于文件开头的偏移量,失败返回-1
练习:
对图片进行加密解密操作
1、打开图片--- open
2、读取图片的前十个字节-- read
3、将读取的10个字节有序地打乱 -- (字符串倒序)
4、将文件指针重新定位在文件开头 -- lseek
5、将打乱地十个字节写入文件 -- write
6、关闭文件 -- close
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
int fp = open("1.bmp",O_RDWR);
if(fp<0)
{
perror("open");
return -1;
}
char buf[64],ret;
read(fp,buf,10);
int i;
for(i=0 ;i<5 ;i++)
{
ret=buf[i];
buf[i]=buf[9-i];
buf[9-i]=ret;
}
lseek(fp,0,SEEK_SET);
write(fp,buf,10);
close(fp);
printf("文件已加密\n");
return 0;
}