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
相关推荐
红石程序员12 分钟前
Python环境管理
开发语言·python
Chennnng14 分钟前
关于python版本,显卡版本,torch版本之间的问题
开发语言·python
rit843249918 分钟前
基于MATLAB的多变量动态矩阵控制(DMC)仿真实现
开发语言·matlab·矩阵
pyniu26 分钟前
项目实站day7--功能之营业额统计,用户数量统计
java·开发语言·spring boot·spring
一周困⁸天.36 分钟前
K8S-NetworkPolicy
java·开发语言
m0_4711996340 分钟前
【JavaScript】前端如何处理服务端部分接口加解密
开发语言·前端·javascript
stanleyrain1 小时前
c++指针问题
开发语言·c++
Tandy12356_1 小时前
手写TCP/IP协议栈——ARP输入处理
c语言·网络协议·tcp/ip·计算机网络
北极糊的狐1 小时前
stream.findFirst().get() 报错 NoSuchElementException
开发语言·python
如意.7591 小时前
【C++】从 I0 库到缓冲区,一篇吃透输入输出
开发语言·c++