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
相关推荐
Magnum Lehar15 分钟前
3d游戏引擎EngineTest的系统实现3
java·开发语言·游戏引擎
Inverse16215 分钟前
C语言_动态内存管理
c语言·数据结构·算法
Mcworld85730 分钟前
java集合
java·开发语言·windows
成功人chen某31 分钟前
配置VScodePython环境Python was not found;
开发语言·python
海绵宝宝贾克斯儿1 小时前
C++中如何实现一个单例模式?
开发语言·c++·单例模式
史迪仔01121 小时前
[python] Python单例模式:__new__与线程安全解析
开发语言·python·单例模式
whoarethenext2 小时前
c/c++的opencv的轮廓匹配初识
c语言·c++·opencv
isyangli_blog2 小时前
(1-4)Java Object类、Final、注解、设计模式、抽象类、接口、内部类
java·开发语言
apocelipes2 小时前
使用libdivide加速整数除法运算
c语言·c++·性能优化·linux编程
三块钱07942 小时前
【原创】基于视觉大模型gemma-3-4b实现短视频自动识别内容并生成解说文案
开发语言·python·音视频