파일이란?
파일(file)은 레코드들의 집합으로, 데이터가 하드 디스크에 영구적으로 저장되는 공간을 의미합니다. C 언어에서 제공하는 다양한 명령어를 활용하면 파일에 여러 가지 방식으로 접근하고 조작할 수 있습니다.
파일에서 수행할 수 있는 기본 연산
C 프로그래밍 언어에서 파일에 대해 수행할 수 있는 대표적인 연산은 다음과 같습니다.
- 파일 이름 지정
- 파일 열기
- 파일 읽기
- 파일 쓰기
- 파일 닫기
파일 처리 기본 문법
1. 파일 포인터 선언 및 파일 열기
먼저 FILE 구조체 포인터를 선언한 뒤, fopen() 함수로 파일을 엽니다.
FILE *파일_포인터;
예를 들면 다음과 같습니다.
FILE *fptr;
파일_포인터 = fopen("파일 이름", "모드");실제 코드 예시입니다.
FILE *fp;
fp = fopen("sample.txt", "w");2. 파일에서 문자 읽기
fgetc() 함수는 파일에서 한 문자씩 읽어올 때 사용합니다.
int fgetc(FILE *fp); // 파일에서 단일 문자 읽기
3. 파일에 문자 쓰기
fputc() 함수는 스트림에 문자를 하나씩 기록할 때 사용합니다.
int fputc(int c, FILE *fp); // 스트림에 개별 문자 쓰기
디렉터리의 파일·폴더 목록 출력 로직
프로그램이 저장된 현재 디렉터리(".")에 있는 파일과 폴더를 화면에 나열하는 핵심 로직은 다음과 같습니다.
dr = opendir(".");
if(dr != NULL){
printf("List of Files & Folders:-\n");
for(d = readdir(dr); d != NULL; d = readdir(dr)){
printf("%s\n", d->d_name);
}
closedir(dr);
}주요 함수 살펴보기
- opendir(".") : 현재 디렉터리를 열고 DIR형 포인터를 반환합니다. 디렉터리를 열지 못하면 NULL을 반환합니다.
- readdir(dr) : 디렉터리에서 항목을 하나씩 순서대로 읽어 struct dirent 포인터로 반환하며, 더 이상 읽을 항목이 없으면 NULL을 반환합니다.
- d->d_name : 현재 항목(파일 또는 폴더)의 이름이 저장되어 있는 멤버 변수입니다.
- closedir(dr) : 열려 있던 디렉터리를 닫고 관련 자원을 해제합니다.
전체 예제 코드
다음은 디렉터리 안의 모든 파일과 폴더를 출력하는 완전한 C 프로그램입니다.
#include<stdio.h>
#include<conio.h>
#include<dirent.h>
int main() {
struct dirent *d;
DIR *dr;
dr = opendir(".");
if(dr!=NULL) {
printf("List of Files & Folders:-\n");
for(d=readdir(dr); d!=NULL; d=readdir(dr)) {
printf("%s\n", d->d_name);
}
closedir(dr);
}
else
printf("\nerror while opening the directory!");
getch();
return 0;
}참고로 dirent.h 헤더는 Linux, Unix 등 POSIX 계열 시스템에서 디렉터리를 다룰 때 사용되며, conio.h와 getch()는 주로 Windows용 컴파일러(Turbo C 등)에서 실행 종료 전 입력 대기를 위해 사용됩니다.
실행 결과
위 프로그램을 실행하면 현재 디렉터리에 존재하는 파일과 폴더 목록이 다음과 같이 출력됩니다.
List of Files & Folders:- . .. accessing array.c accessing array.exe accessing array.o bhanu.txt C Programs convert 2 digit no into english word.c convert 2 digit no into english word.exe convert 2 digit no into english word.o DATA delete vowels in string.c delete vowels in string.exe delete vowels in string.o emp.txt EVEN ex.c ex.exe ex.o example pro.c example pro.exe example pro.o fibbinoci serie.c fibbinoci serie.exe fibbinoci serie.o file file example1.c file example1.exe file example1.o file example2.c file example2.exe file example2.o implicit conversion.c implicit conversion.exe implicit conversion.o leap year.c leap year.exe leap year.o little n big endian.c little n big endian.exe little n big endian.o work out examples