写数据
write(
2):
#include <unistd.h>
ssize_t write(
int fd,
const void *buf, size_t count);
功能:向文件写数据
参数:
fd:指定了具体的文件
buf:指定了内容存放的地址,将这里的内容写到文件
count:指定了文件写入的字节数
返回值:-
1 错误 errno被设置
成功 实际写入的字节数
#include <stdio.h>
#include <p_file.h>
#include <string.h>
int main(
int argc,
char *argv[]) {
char *msg =
"this is a test!\n";
int fd =open(argv[
1], O_WRONLY);
if(fd == -
1) {
perror(
"open");
return -
1;
}
write(fd, msg,
strlen(msg));
close(fd);
return 0;
}
读数据:
read(
2):
#include <unistd.h>
ssize_t read(
int fd,
void *buf, size_t count);
功能:从文件中读取数据
参数:
fd:指定了具体的文件,从这个文件里读取数据,
buf:将读取的数据存放在buf指定的地址空间里
count:向系统申请的要读取的字节数
返回值:实际读取到的字节数,
0 到达了文件的末尾
-
1 错误 errno被设置
#include <stdio.h>
#include <p_file.h>
#include <string.h>
int main(
int argc,
char *argv[]) {
char buf[
128];
int fd =open(argv[
1], O_RDONLY);
if(fd == -
1) {
perror(
"open");
return -
1;
}
int r = read(fd, buf,
128);
write(
1, buf, r);
close(fd);
return 0;
}