C fdopen() 디스크립터에서 스트림 포인터 구하기 함수
디스크립터에서 파일 스트림 포인터를 구합니다. 즉, open()함수로 구한 디스크립터의 값에서 fopen()으로 구하는 FILE * 포인터 값을 구합니다.
- 헤더: stdio.h
- 형태: FILE *fdopen(int fildes, const char *mode)
- 인수: int 파일 디스크립터
char *mode 파일 열기를 위한 옵션
- 반환: FILE * 포인터 또는 실패 시 NULL
파일 열기 옵션 mode
mode |
설명 |
"r" |
읽기 전용. 파일이 반드시 있어야 합니다. |
"r+" |
읽기와 쓰기용으로 열기 |
"w" |
쓰기 전용. 파일이 없으면 생성되고, 파일이 있다면 기존 내용은 지워집니다. |
"w+" |
읽기와 쓰기용으로 열기 |
"a" |
내용 추가. 파일이 없으면 생성되고, 파일이 있다면 기존 내용 뒤에 추가됩니다. |
"a+" |
내용 추가와 함께 읽기 가능 |
C언어 fdopen() 함수 예제
///////////////////////////////////////////////////////////// test.c
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
int file_size( int fd) // 파일 디스크립터로 파일 크기를 구합니다.
{
FILE *fp;
int sz_file;
fp = fdopen( fd, "r");
fseek( fp, 0L, SEEK_END);
sz_file = ftell( fp);
lseek( fd, 0, SEEK_SET); // 반드시 lseek()로 읽기 포인터를 처음으로
fclose( fp);
return( sz_file);
}
int main( void)
{
char buff[1024];
int fd;
fd = open( "test.c", O_RDONLY, 0644);
printf( "file size=%d\n", file_size( dup( fd)));
while( 0 < read( fd, buff, 1024)) // 파일 내용을 출력
printf( "%s\n", buff);
close( fd);
}
C언어 fdopen() 예제 실행 결과
]$ ./a.out
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
int file_size( int fd) // 파일 디스크립터로 파일 크기를 구합니다.
{
FILE *fp;
int sz_file;
fp = fdopen( fd, "r");
fseek( fp, 0L, SEEK_END);
sz_file = ftell( fp);
lseek( fd, 0, SEEK_SET); // 반드시 lseek()로 읽기 포인터를 처음으로
fclose( fp);
return( sz_file);
}
int main( void)
{
char buff[1024];
int fd;
fd = open( "test.c", O_RDONLY, 0644);
printf( "file size=%d\n", file_size( dup( fd)));
while( 0 < read( fd, buff, 1024)) // 파일 내용을 출력
printf( "%s\n", buff);
close( fd);
}
]$