系统调用——文件操作相关函数

古城微笑少年丶 2024-03-26 20:23 126阅读 0赞

1.open

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

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

  1. //头文件
  2. #include <sys/types.h>
  3. #include <sys/stat.h>
  4. #include <fcntl.h>
  5. //接口
  6. int open(const char *pathname, int flags);
  7. 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()
    {

    1. umask(0);
    2. int fd = open("log.txt", O_WRONLY | O_CREAT, 0666);
    3. printf("open success, fd: %d\n", fd);
    4. return 0;

    }

0bd3b0b8e5220815c299ccd3958573c6.png

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

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

2.close

关闭文件

  1. //头文件
  2. #include <unistd.h>
  3. //接口
  4. int close(int fd);
  5. RETURN VALUE:
  6. close() returns zero on success. On error, -1 is returned, and errno is set appropriately.

3.write

write - write to a file descriptor

  1. //头文件
  2. #include <unistd.h>
  3. //接口
  4. ssize_t write(int fd, const void *buf, size_t count);

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

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

log.txt:

94288230a8d265f1a7ff66d81b6a620d.png

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

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

O_APPEND:

606925902c4e6bcd2abe21d53ae17492.png

O_TRUNC:

7f16c3c943232b535e673c95e0dff74a.png

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

面试题

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

  1. #include <sys/types.h>
  2. #include <sys/stat.h>
  3. #include <fcntl.h>
  4. #include <unistd.h>
  5. int main()
  6. {
  7. int fd = open("log.txt", O_RDWR | O_TRUNC);
  8. close(fd);
  9. return 0;
  10. }

4.read

read - read from a file descriptor

  1. //头文件
  2. #include <unistd.h>
  3. //接口
  4. ssize_t read(int fd, void *buf, size_t count);

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

4d65fa0cceb77229abf1a04580c920c9.png

  1. int main()
  2. {
  3. umask(0);
  4. int fd = open("log.txt", O_RDWR | O_CREAT, 0666);
  5. // const char* str = "aa\n";
  6. // ssize_t s = write(fd, str, strlen(str));
  7. printf("open success, fd: %d\n", fd);
  8. char buffer[64];
  9. memset(buffer, '\0', sizeof(buffer));
  10. read(fd, buffer, sizeof(buffer));
  11. printf("%s\n", buffer);
  12. close(fd);
  13. return 0;
  14. }

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

181b09c6561466b4e9823f036dcd2cc4.png

发表评论

表情:
评论列表 (有 0 条评论,126人围观)

还没有评论,来说两句吧...

相关阅读