open close read write lseek函数的用法

1:open 函数

头文件 #include<fcntl.h>

int open(const cahr *pathname  /*被打开的文件*/

                        const char flags, 

);

 

 

/*
* test.c
*
* Created on: Jun 26, 2012
* Author: linux
*/
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<fcntl.h>
int main() {
char buf_write[] = "abcedfg";
char buf_read[10];
int fd;
if ((fd = open("/test/hello.txt", O_RDWR, 0666)) == 0) {
printf("error");
close(fd);
}
int len = strlen(buf_write)+1;
//int len=5;
int size = write(fd, buf_write, len);
printf("%d\n", size);
//puts(buf_write);
lseek(fd, 0, SEEK_SET);
size = read(fd, buf_read, len);
puts(buf_read);
close(fd);
return 0;
}

这些函数都是Linux系统调用,用于在用户空间程序和内核空间之间进行数据传输、设备控制等操作。 1. open(): 打开一个文件或设备,返回该文件或设备的文件描述符,该描述符用于后续的读、写、控制和关闭操作。语法如下: ``` #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> int open(const char *pathname, int flags); ``` 2. close(): 关闭一个文件或设备,释放该文件或设备占用的系统资源。语法如下: ``` #include <unistd.h> int close(int fd); ``` 3. read(): 从一个文件或设备中读取数据到指定的缓冲区中,返回实际读取的字节数。语法如下: ``` #include <unistd.h> ssize_t read(int fd, void *buf, size_t count); ``` 4. write(): 将数据从指定的缓冲区中写入到一个文件或设备中,返回实际写入的字节数。语法如下: ``` #include <unistd.h> ssize_t write(int fd, const void *buf, size_t count); ``` 5. lseek(): 在一个文件或设备中定位到指定的位置,返回新的位置偏移量。语法如下: ``` #include <unistd.h> off_t lseek(int fd, off_t offset, int whence); ``` 6. ioctl(): 对一个设备进行控制和定位操作,需要使用特定的命令码,并可携带相应的参数。语法如下: ``` #include <sys/ioctl.h> int ioctl(int fd, unsigned long request, ...); ``` 这些函数Linux系统编程中非常常用,尤其是在设备驱动开发中。熟练掌握这些函数使用方式和原理,对于开发高质量的Linux应用程序和驱动非常有帮助。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值