1.文件描述符与文件指针
/*
文件指针 FILE* fp
文件描述符 int
STDIN_FILENO stdin
SDTOUT_FILENO stdout
STDERR_FILENO stderr
fileno 文件指针->文件描述符
fdopen 文件描述符->文件指针
*/
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
printf("fileno(stdin)= %d\n",fileno(stdin));
return 0;
}
2.文件的系统调用close、open、creat、read、write
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
//#define ERR_EXIT(m) (perror(m),exit(EXIT_FAILURE))
#define ERR_EXIT(m) \
do \
{ \
perror(m); \
exit(EXIT_FAILURE); \
}while(0)
int main(int argc, char *argv[])
{
int fd;
fd = open("test.txt",O_RDONLY);
/*
if(fd == -1)
{
fprintf(stderr,"open error!errorno is %d,%s\n",errno,strerror(errno));
exit(EXIT_FAILURE);
}
*/
/*
if(fd == -1)
{
perror("open error!\n");
exit(EXIT_FAILURE);
}
*/
if(fd == -1)
ERR_EXIT("open error!");
printf("open succ\n");
return 0;
}
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#define ERR_EXIT(m) \
do \
{ \
perror(m); \
exit(EXIT_FAILURE); \
}while(0)
int main(int argc, char *argv[])
{
umask(0);
int fd;
fd = open("test.txt",O_WRONLY | O_CREAT,0666);
if(fd == -1)
ERR_EXIT("open error!");
printf("open succ\n");
close(fd);
return 0;
}