1.文件与I/O(一)
文件描述符
c函数库-文件指针
FILE* fp stdin stdout stderr
系统调用-文件描述符
int STDIN_FILENO STDOUT_FILENO STDERR_FILENO
文件描述符与文件指针转换
#include<stdio.h>
#include<stdlib.h>
int main()
{
printf("fileno(stdin)=%d",fileno(stdin));
return 0;
}
文件系统调用
open系统调用
#include<stdio.h>
#include<stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<errno.h>
#include<string.h>
int main()
{
int fd;
fd=open("text.txt",O_RDONLY);
if(fd==-1){
fprintf(stderr,"open error with errno=%d %s\n",errno,strerror(errno));
exit(EXIT_FAILURE);
}
printf("open success\n");
return 0;
}
#include<stdio.h>
#include<stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<errno.h>
#include<string.h>
//定义的打开错误的宏
#define ERROR_EXIT(m) (perror(m),exit(EXIT_FAILURE))
int main()
{
int fd;
fd=open("text.txt",O_RDONLY);
/* if(fd==-1){
fprintf(stderr,"open error with errno=%d %s\n",errno,strerror(errno));
exit(EXIT_FAILURE);
}*/
//自定义一个宏函数
if(fd==-1){
ERROR_EXIT("open error");
}
printf("open success\n");
return 0;
}
打开文件方式
访问权限
在这里插入图片描述
ulimit-a 一个进程可以打开的文件数
close系统调用
#include<stdio.h>
#include<stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<errno.h>
#include<string.h>
#define ERROR_EXIT(m) (perror(m),exit(EXIT_FAILURE))
int main()
{
umask(0);
int fd;
//1.文件名 2.文件打开方式 3.文件赋予的权限
fd=open("text.txt",O_WRONLY| O_CREAT,0666);
if(fd==-1){
ERROR_EXIT("open fail");
}
printf("open success\n");
return 0;
}