您的位置:首页 > 运维架构 > Linux

linux系统编程-文件与IO(一)

2014-04-29 13:47 330 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: