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
相关推荐
偷光10 小时前
浏览器中的隐藏IDE: Elements (元素) 面板
开发语言·前端·ide·php
DKPT10 小时前
JVM栈溢出和堆溢出哪个先满?
java·开发语言·jvm·笔记·学习
gopyer14 小时前
180课时吃透Go语言游戏后端开发6:Go语言的循环语句
开发语言·游戏·golang·循环语句
楼田莉子17 小时前
Qt开发学习——QtCreator深度介绍/程序运行/开发规范/对象树
开发语言·前端·c++·qt·学习
韩立学长18 小时前
【开题答辩实录分享】以《基于python的奶茶店分布数据分析与可视化》为例进行答辩实录分享
开发语言·python·数据分析
天若有情67318 小时前
C++空值初始化利器:empty.h使用指南
开发语言·c++
远远远远子18 小时前
类与对象 --1
开发语言·c++·算法
无敌最俊朗@18 小时前
C/C++ 关键关键字面试指南 (const, static, volatile, explicit)
c语言·开发语言·c++·面试
2401_8315017318 小时前
Python学习之day03学习(文件和异常)
开发语言·python·学习
酷~18 小时前
C语言模拟面向对象编程方法之多态
c语言·开发语言