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
相关推荐
kyle~13 小时前
工业以太网协议---EtherCAT
开发语言·c++·网络协议·机器人·ros2
say_fall13 小时前
深入理解AVL树:平衡调整机制与性能优化实战
开发语言·数据结构·c++·学习
赖在沙发上的熊13 小时前
Python数据序列
开发语言·python
Hello--_--World13 小时前
Js面试题目录表
开发语言·javascript·ecmascript
聆风吟º13 小时前
【C标准库】深入理解C语言strcmp函数:字符串比较的核心用法
c语言·开发语言·库函数·strcmp
weixin_4460235613 小时前
C语言入门:发展历程与编程应用
c语言·基础知识·发展历程·语法结构·编程应用
Fanfanaas13 小时前
Linux 进程篇 (四)
linux·运维·服务器·开发语言·c++·学习
Sylvia-girl13 小时前
C++中类与对象
开发语言·c++
良木生香13 小时前
【C++初阶】:泛型编程的代表作---C++初阶模板
c语言·开发语言·数据结构·c++·算法
网域小星球14 小时前
C++ 从 0 入门(一)|C++ 基础语法、命名空间、引用、IO 输入输出
开发语言·c++·引用·命名空间·cin/cout