파일 디스크립터 반환받기:파일 열기
int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);
O_RDONLY:읽기 전용으로 열기
O_WRONLY:쓰기 전용으로 열기
O_RDWR:읽기 쓰기 전용으로 열기
O_CREAT:파일이 없다면 생성하기(mode_t mode 필수)
O_TRUNC:기존 파일 내용 삭제
O_APPEND:파일의 끝 지점부터 쓰기 시작(추가하기)
Parameter
Return
int close(int fd);
Parameter
Return
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
int main() {
int fd; //변수 선언
// 파일을 열고 파일 디스크립터를 얻음
fd = open("example.txt", O_RDONLY);
if (fd == -1) {
perror("Failed to open the file");
return 1;
}
printf("File descriptor: %d\n", fd);
// 파일을 닫음
if (close(fd) == -1) {
perror("Failed to close the file");
return 1;
}
return 0;
}
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileDescriptor;
import java.io.IOException;
public class File_2 {
public static void main(String[] args) {
try {
String filePath = "example.txt";
// 파일 디스크립터로 파일 열기
FileInputStream fis = new FileInputStream(filePath);
FileDescriptor fd = fis.getFD();
// 파일 디스크립터 값 출력
System.out.println("파일 디스크립터 값: " + fd.toString());
// 파일 디스크립터를 이용한 파일 읽기
byte[] buffer = new byte[1024];
int bytesRead = fis.read(buffer);
System.out.println("파일 내용: " + new String(buffer, 0, bytesRead));
// 파일 닫기
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
f_name = "example.txt"
fileObject = open(f_name, "r")
print("The file descriptor for %s is %s" % (f_name, fileObject.fileno()))
FILE *fopen(const char *pathname, const char *mode);
Parameter
Return
int fclose(FILE *stream);
Parameter
Return
#include <stdio.h>
int main() {
FILE *file; // 파일 포인터 선언
// 파일 열기 시도
file = fopen("example.txt", "w"); // "example.txt" 파일을 쓰기 모드로 열기
if (file == NULL) {
printf("파일을 열 수 없습니다.\n");
return 1; // 오류 코드 반환
}
// 파일에 데이터 쓰기
fprintf(file, "안녕하세요, 파일에 쓰는 예제입니다.\n");
// 파일 닫기
fclose(file);
return 0; // 프로그램 종료
}
FILE *fopen(int fd, const char *mode);
Parameter
Return
파일 포인터에서 파일 디스크립터 반환 받기
int fileno(FILE *stream);
Parameter
Return
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main() {
FILE *file; // 파일 포인터
int fd; // 파일 디스크립터
// 파일 열기 시도
file = fopen("example.txt", "r");
if (file == NULL) {
perror("파일 열기 오류");
return 1;
}
// 파일 포인터를 파일 디스크립터로 변환
fd = fileno(file);
printf("file descriptor: %d\n", fd);
// 파일 닫기
fclose(file);
return 0;
}