(一)发行版:Ubuntu16.04.7
(二)记录:
close函数
关闭fd标识符的文件
(1)close函数具有返回值
(2)包含头文件
(3)编译运行
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc,char *argv[])
{
//argc 表示命令行中参数的个数
//argv 表示命令行中的参数
int fd;
int close_fd;
//没有a.c所以创建a.c
fd = open("a.c",O_CREAT|O_RDWR,0666);
if(fd == -1)
printf("fail to open a.c\n");
else
printf("open a.c successfully:%d\n",fd);
//关闭文件
close_fd=close(fd);
if(close_fd == 0)
printf("close a.c successfully\n");
else
printf("fail to close a.c\n");
return 0;
}
read函数
将fd标识文件中count字节大小的数据拷贝到buf。
(1)参数:
(2)返回值:ssize_t
(3)编译运行
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc,char *argv[])
{
//argc 表示命令行中参数的个数
//argv 表示命令行中的参数
int fd;
int close_fd;
ssize_t read_byte;
char read_buf[32]={0};
//没有a.c所以创建a.c
fd = open("readme.txt",O_RDWR);
if(fd == -1)
printf("fail to open readme.txt\n");
else
printf("open readme.txt successfully:%d\n",fd);
//读取文件
read_byte=read(fd,read_buf,32);
if(fd == -1)
printf("fail to read readme.txt");
else
{
printf("read %d bytes\n",read_byte);
for(int i=0;i<32;i++)
printf("%c",read_buf[i]);
printf("\n");
}
//关闭文件
close_fd=close(fd);
if(close_fd == 0)
printf("close file successfully\n");
else
printf("fail to close file\n");
return 0;
}
write函数 (写入数据之后需要关闭文件,再打开文件才能读)
(1)参数:
(2)返回值:
(3)编译运行:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc,char *argv[])
{
int fd;
int close_fd;
ssize_t read_byte;
ssize_t write_byte;
char read_buf[11]={0};
char write_buf[11]="hello world";
fd = open("writeme.txt",O_RDWR|O_CREAT,0666);
if(fd == -1)
printf("fail to open writeme.txt\n");
else
printf("open writeme.txt successfully:%d\n",fd);
//写入数据
write_byte=write(fd,write_buf,11);
if(write_byte == -1)
printf("fail to write\n");
else
printf("write %d bytes successfully\n",write_byte);
//关闭文件
close_fd=close(fd);
if(close_fd == 0)
printf("close file successfully\n");
else
printf("fail to close file\n");
return 0;
}
(4)如果要在终端打印hello
write(1,"hello\n",6);
因为 0 1 2分别代表的是
0---------------------------标准输入
1---------------------------标准输出
2---------------------------标准出错
(三)命令: