open/read/write/close函数
Linux 下文件读写
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);
#include <fcntl.h> #include <stdio.h> #include <unistd.h> int main() { int fd;
// 举例:
int fd = open("./app.c", O_RDONLY) // 只读
int fd = open("./app.c", O_RDWR) // 读写
// 1. 创建文件 file1.txt,权限为 0644 (rw-r--r--) fd = open("file1.txt", O_WRONLY | O_CREAT, 0644); if (fd == -1) { perror("open file1 failed"); return 1; } close(fd); // 2. 创建私有文件 file2.txt,仅所有者可读写 (0600) fd = open("file2.txt", O_RDWR | O_CREAT, 0600); if (fd == -1) { perror("open file2 failed"); return 1; } close(fd); // 3. 使用符号常量(更易读) // S_IRUSR | S_IWUSR 等价于 0600 fd = open("file3.txt", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); if (fd == -1) { perror("open file3 failed"); return 1; } close(fd); printf("三个文件创建成功。\n"); return 0; }
write写文件:
#include <unistd.h> ssize_t write(int fd, const void *buf, size_t count);
返回值:如果成功将返回写入的字节数(0 表示未写入任何字节),如果此数字小于 count 参数,这不是错误,譬如磁盘空间已满,可能会发生这种情况;如果写入出错,则返回-1。
read读文件:
#include <unistd.h> ssize_t read(int fd, void *buf, size_t count)
首先使用 read 函数需要先包含 unistd.h 头文件。
如果读取成功将返回读取到的字节数,实际读取到的字节数可能会小于 count 参数指定的字节数,也有可能会为 0,譬如进行读操作时,当前文件位置偏移量已经到了文件末尾。
lseek位置偏移:
#include <sys/types.h> #include <unistd.h> off_t lseek(int fd, off_t offset, int whence); 首先调用 lseek 函数需要包含<sys/types.h>和<unistd.h>两个头文件。
fd:文件描述符。
offset:偏移量,以字节为单位。
whence:用于定义参数 offset 偏移量对应的参考值,该参数为下列其中一种(宏定义):
⚫ SEEK_SET:读写偏移量将指向 offset 字节位置处(从文件头部开始算);
⚫ SEEK_CUR:读写偏移量将指向当前位置偏移量 + offset 字节位置处,offset 可以为正、也可以为
负,如果是正数表示往后偏移,如果是负数则表示往前偏移;
⚫ SEEK_END:读写偏移量将指向文件末尾 + offset 字节位置处,同样 offset 可以为正、也可以为负,
如果是正数表示往后偏移、如果是负数则表示往前偏移。
返回值:成功将返回从文件头部开始算起的位置偏移量(字节为单位),也就是当前的读写位置;发生
错误将返回-1。
使用示例: (1)将读写位置移动到文件开头处: off_t off = lseek(fd, 0, SEEK_SET); if (-1 == off) return -1; (2)将读写位置移动到文件末尾: off_t off = lseek(fd, 0, SEEK_END); if (-1 == off) return -1; (3)将读写位置移动到偏移文件开头 100 个字节处: off_t off = lseek(fd, 100, SEEK_SET); if (-1 == off) return -1; (4)获取当前读写位置偏移量: off_t off = lseek(fd, 0, SEEK_CUR); if (-1 == off) return -1; 函数执行成功将返回文件当前读写位置。

浙公网安备 33010602011771号