Computer >> 컴퓨터 >  >> 프로그래밍 >> C 프로그래밍

C 언어 파일 처리 기초: 쓰기, 읽기, 추가하기 완벽 정리

C 언어에서 파일을 다루는 것은 프로그램이 데이터를 영구적으로 저장하고 필요할 때 다시 불러올 수 있게 해주는 핵심 기능입니다. 이 글에서는 C에서 가장 많이 사용되는 기본적인 파일 처리 작업 세 가지를 예제 코드와 함께 단계별로 살펴보겠습니다.

  • 파일에 데이터 쓰기
  • 파일에서 데이터 읽기
  • 파일에 내용 추가(append)하기

1. 파일에 쓰기

파일에 내용을 쓰려면 fopen() 함수를 "w"(쓰기 모드)로 호출한 뒤, fprintf()로 데이터를 기록하고 fclose()로 파일을 닫으면 됩니다. 아래 예제를 통해 전체 흐름을 확인해 보세요.

예제 코드

#include <stdio.h>
int main() {
    FILE *fp;
    char *filename = "sample.txt";
    char *content = "Hey there! You've successfully created a file with content in c programming language.";
    /* 쓰기 모드로 파일 열기 */
    fp = fopen(filename, "w");
    if( fp == NULL ) {
        printf("%s: failed to open. \n", filename);
        return -1;
    } else {
        printf("%s: opened in write mode.\n", filename);
    }
    /* 파일에 내용 쓰기 */
    fprintf(fp, "%s\n", content);
    if( !fclose(fp) )
        printf("%s: closed successfully.\n", filename);
    return 0;
}

실행 결과

sample.txt: opened in write mode.
sample.txt: closed successfully.

참고: "w" 모드로 파일을 열면 해당 파일이 이미 존재할 경우 기존 내용이 모두 삭제되므로 주의해야 하며, 파일이 없으면 새로 생성됩니다.

2. 파일에서 읽기

파일의 내용을 읽으려면 fopen()"r"(읽기 모드)로 호출하고, fgetc() 함수로 한 문자씩 EOF(파일 끝)에 도달할 때까지 반복해서 읽으면 됩니다.

먼저 다음과 같은 내용을 담은 file_read.txt 파일을 준비합니다:

You have opened a file using C programming language, in read-only mode.

예제 코드

#include <stdio.h>
int main() {
    FILE *fp;
    char *filename = "file_read.txt";
    char ch;
    /* 읽기 모드로 파일 열기 */
    fp = fopen(filename, "r");
    if (fp == NULL) {
        printf("%s does not exists \n", filename);
        return;
    } else {
        printf("%s: opened in read mode.\n\n", filename);
    }
    while ((ch = fgetc(fp) )!= EOF) {
        printf ("%c", ch);
    }
    if (!fclose(fp))
        printf("\n%s: closed.\n", filename);
    return 0;
}

실행 결과

file_read.txt: opened in read mode.
You have opened a file using C programming language, in read-only mode.
file_read.txt: closed.

파일이 존재하지 않으면 fopen()이 NULL을 반환하므로, 이를 반드시 확인하여 오류를 처리하는 것이 좋습니다.

3. 파일에 내용 추가하기(Append)

기존 파일의 내용을 유지하면서 새로운 내용을 뒤에 덧붙이려면 "a"(추가 모드)를 사용합니다. 아래 예제는 파일의 현재 내용을 출력한 후, 새 문장을 추가하고 다시 전체 내용을 확인하는 과정을 보여줍니다.

먼저 다음과 같은 내용을 담은 file_append.txt 파일을 준비합니다:

This text was already there in the file.

예제 코드

#include <stdio.h>
int main() {
    FILE *fp;
    char ch;
    char *filename = "file_append.txt";
    char *content = "This text is appeneded later to the file, using C programming.";
    /* 먼저 읽기 모드로 열어 기존 내용 확인 */
    fp = fopen(filename, "r");
    printf("\nContents of %s -\n\n", filename);
    while ((ch = fgetc(fp) )!= EOF) {
        printf ("%c", ch);
    }
    fclose(fp);
    /* 추가 모드로 열어 새 내용 덧붙이기 */
    fp = fopen(filename, "a");
    fprintf(fp, "%s\n", content);
    fclose(fp);
    /* 다시 읽어 최종 내용 확인 */
    fp = fopen(filename, "r");
    printf("\nContents of %s -\n", filename);
    while ((ch = fgetc(fp) )!= EOF) {
        printf ("%c", ch);
    }
    fclose(fp);
    return 0;
}

실행 결과

Contents of file_append.txt -
This text was already there in the file.
Appending content to file_append.txt...
Content of file_append.txt after 'append' operation is -
This text was already there in the file.
This text is appeneded later to the file, using C programming.

마무리

정리하면, C에서 파일 처리의 기본 패턴은 fopen()으로 목적에 맞는 모드("w": 쓰기, "r": 읽기, "a": 추가)를 지정하여 파일을 열고, fprintf()fgetc() 등의 함수로 입출력을 수행한 뒤, 마지막에 반드시 fclose()로 파일을 닫는 것입니다. 또한 파일 포인터가 NULL인지 항상 검사하여 파일이 없거나 열기에 실패한 상황에 대비하는 습관을 들이면 더 안전한 코드를 작성할 수 있습니다.