原
Linux系统调用接口
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 参数解析
1.pathname:要打开或创建的目标文件
2.flags:打开文件时可以传入多个参数进程,用下面的一个或者多个常量进行“或”运算,构成flags.
参数:
O_RDONLY 只读
O_WRONLY 只写
O_RDWR 读写打开
O_CREAT 文件不存在创建它
O_APPEND 追加写
- 1
- 2
- 3
- 4
- 5
- 返回值: 成功返回新打开文件的描述符
失败返回 -1 - open函数具体使用哪个由具体应用场景相关,如目标文件不存在,需要open创建,则选择三个参数的open,它的第三个参数表示创建文件的默认权限,否则使用两个参数的open。
close
#include <unistd.h>
int close(int fd);
- 1
- 2
- 3
- 4
- 参数fd为要关闭文件的文件描述符
- 返回值:成功返回 0,失败返回-1
write
#include <unistd.h>
ssize_t pwrite(int fildes, const void *buf, size_t nbyte, off_t offset); ssize_t write(int fildes, const void *buf, size_t nbyte);
- 1
- 2
- 3
- 4
- 5
- 6
- 使用
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<string.h>
int main()
{
int fd = open(“myfile”,O_WRONLY | O_CREAT, 0644);
if(fd < 0)
{
perror(“open”);
return 1;
}
int count = 3;
const char* buf = “hello taotao\n”;
while(count–)
{
write(fd,buf,strlen(buf));
}
close(fd);
return 0;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
上述代码使用open打开并创建一个新文件并在新文件中写入3行hello taotao。
read
#include <unistd.h>
ssize_t pread(int fildes, void *buf, size_t nbyte, off_t offset); ssize_t read(int fildes, void *buf, size_t nbyte);
- 1
- 2
- 3
- 4
- 5
- 使用
#include<string.h>
#include<stdio.h>
#include<sys/types.h>
#include<stdlib.h>
#include<sys/stat.h>
#include<unistd.h>
#include<fcntl.h>
int main()
{
int fd = open(“myfile”,O_RDONLY);
if(fd < 0)
{
perror(“open”);
exit(1);
}
const char* msg = “hello taotao\n”;
char buf[1024];
while(1)
{
ssize_t s = read(fd,buf,strlen(msg));
if(s > 0)
{
printf("%s",buf);
}else{
buf[s] = 0;
break;
}
}
close(fd);
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
</div>
<link href="https://csdnimg.cn/release/phoenix/mdeditor/markdown_views-7b4cdcb592.css" rel="stylesheet">
</div>
</article>