linux c--文件IO

2021-06-30

系统通过文件描述符(file descriptor:一个非负的整型值)将各种IO类型统一起来。这些IO类型包括普通文件,终端,管道,FIFO,设备,套接字等等。有了文件描述符,就可以使用一套统一的IO函数:open/read/write/close等。

open函数

1
2
3
4
5
6
#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);

open函数说明:

参数:

返回值:若所有欲核查的权限都通过了检查则返回0 值, 表示成功, 只要有一个权限被禁止则返回-1.

错误代码:

附加说明:使用 access()作用户认证方面的判断要特别小心, 例如在access()后再作open()空文件可能会造成系统安全上的问题. 使用完记得使用close函数关闭文件描述符

范例

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
main()
{
    int fd, size;
    char s[] = "Linux Programmer!\n", buffer[80];
    fd = open("/tmp/temp", O_WRONLY|O_CREAT);
    write(fd, s, sizeof(s));
    close(fd);
    fd = open("/tmp/temp", O_RDONLY);
    size = read(fd, buffer, sizeof(buffer));
    close(fd);
    printf("%s", buffer);
}

执行

1
Linux Programmer!

close函数

1
2
3
#include <unistd.h>

int close(int fd);

函数说明:当使用完文件后若已不再需要则可使用 close()关闭该文件, 二close()会让数据写回磁盘, 并释放该文件所占用的资源. 参数fd 为先前由open()或creat()所返回的文件描述词.

返回值:若文件顺利关闭则返回0, 发生错误时返回-1.

错误代码:EBADF 参数fd 非有效的文件描述词或该文件已关闭.

附加说明:虽然在进程结束时, 系统会自动关闭已打开的文件, 但仍建议自行关闭文件, 并确实检查返回值.

参考链接

http://c.biancheng.net/cpp/html/238.html http://c.biancheng.net/cpp/html/229.html

words: 1646 tags: linux c