c open close read write lseek

几个系统函数
open

 int open(const char *pathname, int flags, ...);   //mode

O_RDONLY 只读
O_WRONLY 只写
O_RDWR 读写
O_CREAT 若不存在创建
O_ APPEND 末尾添加

如果是有O_CREAT,最后参数是权限参数,否则忽略
S_IRWXU 0700 用户权限读写执行

close

int close(int fd);

#include 
#include 
#include 
 
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

size_t read (int fd, void* buf, size_t cnt);

write

size_t write (int fd, void* buf, size_t cnt); 

lseek

off_t lseek(int fd, off_t offset, int whence);

whence
SEEK_CUR 当前偏移 最后指向当前偏移+offset
SEEK_SET 把offset设为当前偏移
SEEK_END 指向结尾 可以用来获取文件大小

#include 
#include 
#include 
#include 
 
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;
}

输出

fd = 3
res = 128
filesize = 256

你可能感兴趣的:(c语言,开发语言)