c open close read write lseek

几个系统函数

open

c 复制代码
 int open(const char *pathname, int flags, ...);   //mode

O_RDONLY 只读
O_WRONLY 只写
O_RDWR 读写
O_CREAT 若不存在创建
O_ APPEND 末尾添加

如果是有O_CREAT,最后参数是权限参数,否则忽略
S_IRWXU 0700 用户权限读写执行

close

c 复制代码
int close(int fd);

c 复制代码
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
 
int main()
{
    int fd = open("test", O_RDONLY | O_CREAT, S_IRWXU);
 
    printf("fd = %d\n", fd);
    if (fd == -1) 
        printf("open failed\n");
    close(fd);
    return 0;
}

read

c 复制代码
size_t read (int fd, void* buf, size_t cnt);

write

c 复制代码
size_t write (int fd, void* buf, size_t cnt); 

lseek

c 复制代码
off_t lseek(int fd, off_t offset, int whence);

whence

SEEK_CUR 当前偏移 最后指向当前偏移+offset

SEEK_SET 把offset设为当前偏移

SEEK_END 指向结尾 可以用来获取文件大小

c 复制代码
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
 
int main()
{
    int fd = open("test", O_RDONLY | O_CREAT,S_IRWXU);
 
    printf("fd = %d\n", fd);
    if (fd == -1) 
        printf("open failed\n");

	char mem[256];
	
	memset(mem,'a',256);
	write(fd,mem,256);
	lseek(fd,128,SEEK_SET);
	memset(mem,0,256);
	int res = read(fd,mem,256);
	printf("res = %d\n", res);
	 int filesize = lseek(fd,0,SEEK_END);
	 printf("filesize = %d\n", filesize);

    close(fd);
    return 0;
}

输出

c 复制代码
fd = 3
res = 128
filesize = 256
相关推荐
AI人工智能+电脑小能手5 分钟前
【大白话说Java面试题 第113题】【并发篇】第13题:说一下乐观锁的优点和缺点?
java·开发语言·面试
lihao lihao18 分钟前
linux线程
java·开发语言·jvm
码云骑士25 分钟前
03-Python可变对象与不可变对象(下)-深浅拷贝的底层真相
开发语言·python
sycmancia27 分钟前
Qt——自定义模型类
开发语言·qt
MATLAB代码顾问32 分钟前
Python数据分析项目实战:销售数据仪表盘
开发语言·python·数据分析
码云骑士33 分钟前
07-Python装饰器从入门到源码(下)-带参数装饰器与wraps
开发语言·python
LAM LAB35 分钟前
【Web】网页如何模拟移动端获取定位\定位模拟测试
开发语言·前端·javascript
小糯米60137 分钟前
C语言文件操作
c语言·开发语言·数据结构
caimouse38 分钟前
Reactos 第 9 章 设备驱动 — 9.4 内核劳务线程
开发语言·windows