#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define BUFF (1024)
int file2fd(const char * path)
{
FILE *fp = NULL;
int fd;
fp = fopen(path, "r");
if (fp == NULL)
{
perror("open file error.");
exit(1);
}
else
{
printf("open file successfully...\n");
}
fd = fileno(fp);
if (-1 == fd)
{
perror("fp to fd error.");
}
else
{
printf("ok fd = %d\n", fd);
exit(1);
}
return 0;
}
int fd2file(const char * path)
{
int fd;
FILE *fp = NULL;
fd = open(path, O_CREAT|O_RDWR, 0666);
if(-1 == fd)
{
perror("open file error.");
return -1;
}
else
{
printf("ok!\n");
}
fp = fdopen(fd, "r");
if (NULL == fp)
{
perror("fd to fp error.");
}
else
{
printf("ok!!!!\n");
return 0;
}
return 0;
}
int main(int argc, const char *argv[])
{
int ret = -1;
char arg[BUFF] = { 0 };
memset(arg, 0, sizeof(arg));
strcpy(arg, argv[1]);
ret = fd2file(arg);
if(ret != 0)
{
fprintf(stderr, "fd2file error %d\n", ret);
return ret;
}
puts("\n\n");
ret = file2fd(arg);
if(ret != 0)
{
fprintf(stderr, "file2fd error %d\n", ret);
return ret;
}
return 0;
}
测试结果
