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
相关推荐
864记忆18 小时前
Qt Widgets 模块中的函数详解
开发语言·qt
white-persist19 小时前
差异功能定位解析:C语言与C++(区别在哪里?)
java·c语言·开发语言·网络·c++·安全·信息可视化
q***728719 小时前
Golang 构建学习
开发语言·学习·golang
hmbbcsm19 小时前
练习python题目小记(五)
开发语言·python
kokunka19 小时前
C#类修饰符功能与范围详解
java·开发语言·c#
仟濹19 小时前
【Java 基础】3 面向对象 - this
java·开发语言·python
Dxy123931021619 小时前
Python一个类的特殊方法有哪些
开发语言·python
爱吃烤鸡翅的酸菜鱼19 小时前
如何用【rust】做一个命令行版的电子辞典
开发语言·rust
不爱学英文的码字机器19 小时前
Rust 并发实战:使用 Tokio 构建高性能异步 TCP 聊天室
开发语言·tcp/ip·rust
redtro9520 小时前
【开发备忘】GeoServer相关两则:发布时间维ImageMosaic+客户端WMS样式
java·开发语言·spring