前言:大佬写博客给别人看,菜鸟写博客给自己看。我是菜鸟
认知1:
stdin → 标准输入 → 键盘文件
stdout → 标准输出 → 显示器文件
stderr → 标准错误 → 显示器文件
注:把显示器以及键盘看作是文件,广义的说:Linux下一切都是文件
1.系统接口的使用(open/close/write/read)
写一段简单的代码来实现一下:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
int fd = open("log.txt",O_CREAT | O_WRONLY | O_TRUNC,0666);
if(fd < 0)
{
perror("open");
exit(1);
}
const char* msg = "hello kivotos\n";
write(fd,msg,strlen(msg));
close(fd);
return 0;
}
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
int fd = open("log.txt",O_RDONLY);
if(fd < 0)
{
perror("open");
exit(1);
}
// const char* msg = "hello kivotos\n";
// write(fd,msg,strlen(msg));
char buffer[64];
int n = read(fd,buffer,sizeof(buffer)-1);
if(n>0)
{
buffer[n] = 0;
printf("%s",buffer);
}
close(fd);
return 0;
}
int open(const char *pathname, int flags, mode_t mode);
pathname:任意路径
flag:常用的有以下几个
O_RDONLY → 只读
O_WRONLY → 只写
O_RDWR → 读写
O_CREAT → 文件不存在则创造(若路径下文件不存在,则一定要加)
O_TRUNC → 将文件中的内容删除并重写
O_APPEND → 在文件新的一行追加
mode:当创建文件时