系统调用——文件操作相关函数
创始人
2024-05-31 21:47:41

1.open

open, creat - open and possibly create a file or device

打开一个文件,也可能创建一个文件,返回文件描述符

//头文件
#include 
#include 
#include 
//接口
int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);

open有两套接口可供使用,下面介绍一下open的参数:

  1. pathname:文件路径(当前文件夹为默认路径)。
  2. flags:文件的打开方式;包括O_RDONLY(只读)、O_WRONLY(只写)、O_RDWR(读写)、O_APPEND(追加)、O_TRUNC(清空)。
  3. mode:八进制权限,如0666表示(rw-rw-rw-),mode一般配合umask函数使用。
#include 
#include 
#include 
#include int main()
{umask(0);int fd = open("log.txt", O_WRONLY | O_CREAT, 0666);printf("open success, fd: %d\n", fd);return 0;
}

执行程序之后,就在当前路径下创建了一个权限为rw-rw-rw的log.txt。

系统中也有默认的umask,如果程序中设置umask值就会使用程序中设置的(就近原则)。

2.close

关闭文件

//头文件
#include 
//接口int close(int fd);
RETURN VALUE:close() returns zero on success.  On error, -1 is returned, and errno is set appropriately.

3.write

write - write to a file descriptor

//头文件
#include 
//接口ssize_t write(int fd, const void *buf, size_t count);

现在我们已经打开了一个文件,那么直接使用write向fd中写入:

const char* str = "hello write\n";
ssize_t s = write(fd, str, strlen(str));

log.txt:

write时要注意打开方式,打开时可以是O_APPEND,也可以是O_TRUNC。

现在log.txt已经写入了"hello write",那么我们看一下O_APPEND和O_TRUNC的不同点:

O_APPEND:

O_TRUNC:

open函数的第二个参数加上O_APPEND选项后,写入的数据会在文件的末尾追加;加上O_TRUNC之后打开文件会先清空文件,然后再向文件中写入。

面试题

写一段程序,清空文件中的数据。

#include 
#include 
#include 
#include int main()
{int fd = open("log.txt", O_RDWR | O_TRUNC);close(fd);return 0;
}

4.read

read - read from a file descriptor

//头文件#include 
//接口
ssize_t read(int fd, void *buf, size_t count);

使用read函数时open函数的第二个参数flags需要改变,O_WRONLY需要改为O_RDONLY或者O_RDWR;这样才能在文件中读取数据。

int main()
{umask(0);int fd = open("log.txt", O_RDWR | O_CREAT, 0666);// const char* str = "aa\n";// ssize_t s = write(fd, str, strlen(str));printf("open success, fd: %d\n", fd);char buffer[64];memset(buffer, '\0', sizeof(buffer));read(fd, buffer, sizeof(buffer));printf("%s\n", buffer);close(fd);return 0;
}

把文件中的数据读取到buffer中:

相关内容

热门资讯

苗族的传统节日 贵州苗族节日有... 【岜沙苗族芦笙节】岜沙,苗语叫“分送”,距从江县城7.5公里,是世界上最崇拜树木并以树为神的枪手部落...
应用未安装解决办法 平板应用未... ---IT小技术,每天Get一个小技能!一、前言描述苹果IPad2居然不能安装怎么办?与此IPad不...
脚上的穴位图 脚面经络图对应的... 人体穴位作用图解大全更清晰直观的标注了各个人体穴位的作用,包括头部穴位图、胸部穴位图、背部穴位图、胳...
阿西吧是什么意思 阿西吧相当于... 即使你没有受到过任何外语培训,你也懂四国语言。汉语:你好英语:Shit韩语:阿西吧(아,씨발! )日...