1 系统IO函数
2 open函数
在文档的第二章(以下命令:man文档,第二章,open函数)
open函数中的errno:
通过perror函数就可以取到errno值所对应的错误内容:
open函数的使用 :
ps:
- 写代码时,想要精确跳转到库函数的文档,可以把光标移动到该函数上,然后Shift+K。
- 当用open函数创建函数时,第三个参数可以指定创建的文件的权限,可是实际权限与本地环境的一个掩码(umask)有关。
查看掩码:umask
更改掩码(临时修改,即只在当前环境生效):umask 数字
实例代码1:
(参考代码:下载资源:linux_learn_1_open.tar.gz )
3 close函数
4
4.1 read函数
read函数的返回值:
- -1 读文件失败
- 0 文件读完了
- >0 读取的字节数
4.2 write函数
参考代码:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main()
{
// open a file that already exists
int fd = open("english.txt", O_RDONLY);
if(fd == -1)
{
perror("open fail!");
exit(1);
}
// create a file -- write
int fd1 = open("newfile", O_CREAT | O_WRONLY, 0664);
if(fd1 == -1)
{
perror("open1 fail!");
exit(1);
}
// create a buf
char buf[2018] = {0};
// read file
int count = read(fd, buf, sizeof(buf)); // read this file to a buf
if(count == -1)
{
perror("read fail!");
exit(1);
}
while(count)
{
// write the data which is reading from file to another file
int ret = write(fd1, buf, count);
printf("write bytes %d\n", ret);
// continue reading file
count = read(fd, buf, sizeof(buf));
}
// close file
close(fd1);
close(fd);
}
6 lseek函数
作用:移动文件指针,获取文件长度。
- 获取文件大小
- 移动文件指针
- 文件拓展(把文件拓展成更大的拓展,拓展只能向后拓展)
文件拓展参考代码:
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
int fd = open("aa", O_RDWR);
if(fd == -1)
{
perror("open file");
exit(1);
}
// get the length of this file
int ret = lseek(fd, 0, SEEK_END);
printf("file length = %d\n", ret);
// extend
ret = lseek(fd, 2000, SEEK_END);
printf("return value %d\n", ret);
// to launch extend, there is a step needed
write(fd, "a", 1);
close(fd);
return 0;
}
被拓展的文件内容样子如下:
这些个蓝色的,被拓展的,又名‘空洞’。这种文件又叫空洞文件。不过打印这种文件时看不到这些个蓝色的。
文件空洞的作用:下载电影时,会有一个文件,电影有多大,文件就有多大,当电影还未下载下来时,这个文件就是一个空洞文件,它是通过文件拓展的方式实现的。