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
相关推荐
galaxy_strive10 小时前
Qt C++插件化编写项目(1)
开发语言·c++·qt
见叶之秋10 小时前
【C++】C++ 核心进阶(一):泛型编程基石 —— 模板初阶与 STL 体系开篇
开发语言·c++
Escalating_xu10 小时前
【Makefile 进阶】从自动发现源文件、模式规则到目录分离与多模块递归构建
linux·开发语言
艾莉丝努力练剑10 小时前
【AI大模型接入SDK】Gemini模型接入知识体系
java·开发语言·网络·人工智能·网络协议·学习·http
传奇开心果编程10 小时前
【Rust入门知识点学与练】第13课:枚举 Enum
开发语言·学习·rust
zhanghaha131410 小时前
Python进阶教程:28_queue 队列模块 零基础超详细教程
java·开发语言·python
司小豆10 小时前
第七课:DeepSeek Harness 服务与依赖注入
java·服务器·开发语言·github·ai编程
ysu_031410 小时前
02-单链表完全指南
c语言·数据结构·算法·leetcode
weixin1997010801610 小时前
[特殊字符]《闲鱼 + 淘宝 + 1688 三平台库存同源:二手ERP主数据治理与超卖防御》(附Python源码)
开发语言·python
ltqshs10 小时前
C语言-链表例程
c语言·开发语言·链表