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

C 언어로 텍스트 파일에서 특정 줄 삭제하는 방법


파일(file)은 디스크 상의 물리적 저장 위치를 의미하고, 디렉터리(directory)는 파일을 체계적으로 관리하기 위한 논리적 경로입니다. 모든 파일은 반드시 하나의 디렉터리 안에 존재합니다.

C 언어에서 파일에 대해 수행할 수 있는 기본 작업은 크게 세 가지입니다.

  • 파일 열기
  • 파일 처리(읽기, 쓰기, 수정)
  • 파일 저장 후 닫기

알고리즘

다음은 C 프로그램으로 파일에서 특정 줄을 삭제하는 전체 절차를 나타낸 알고리즘입니다.

1단계 - 실행 시점에 파일 경로와 삭제할 줄 번호를 입력받습니다.

2단계 - 원본 파일을 읽기 모드로 열고 소스 파일 포인터에 저장합니다.

3단계 - 임시 파일을 쓰기 모드로 생성하여 열고, 그 참조를 임시 파일 포인터에 저장합니다.

4단계 - 줄 번호를 추적하기 위해 count 변수를 1로 초기화합니다.

5단계 - 소스 파일에서 한 줄을 읽어 버퍼에 저장합니다.

6단계 - 현재 줄이 삭제 대상 줄이 아니라면(line != count), 버퍼의 내용을 임시 파일에 기록합니다.

7단계 - count 값을 1 증가시킵니다(count++).

8단계 - 소스 파일의 끝에 도달할 때까지 5~7단계를 반복합니다.

9단계 - 소스 파일과 임시 파일을 모두 닫습니다.

10단계 - 원본 소스 파일을 삭제합니다.

11단계 - 임시 파일의 이름을 소스 파일 경로로 변경합니다.

프로그램 코드

다음은 파일에서 특정 줄을 삭제하는 C 프로그램의 전체 코드입니다.

#include <stdio.h>
#include <stdlib.h>
#define BUFFER_SIZE 1000
void deleteLine(FILE *src, FILE *temp, const int line);
void printFile(FILE *fptr);
int main(){
    FILE *src;
    FILE *temp;
    char ch;
    char path[100];
    int line;
    src=fopen("cprogramming.txt","w");
    printf("enter the text.press cntrl Z:\n");
    while((ch = getchar())!=EOF){
        putc(ch,src);
    }
    fclose(src);
    printf("Enter file path: ");
    scanf("%s", path);
    printf("Enter line number to remove: ");
    scanf("%d", &line);
    src = fopen(path, "r");
    temp = fopen("delete.tmp", "w");
    if (src == NULL || temp == NULL){
        printf("Unable to open file.\n");
        exit(EXIT_FAILURE);
    }
    printf("\nFile contents before removing line.\n\n");
    printFile(src);
    // Move src file pointer to beginning
    rewind(src);
    // Delete given line from file.
    deleteLine(src, temp, line);
    /* Close all open files */
    fclose(src);
    fclose(temp);
    /* Delete src file and rename temp file as src */
    remove(path);
    rename("delete.tmp", path);
    printf("\n\n\nFile contents after removing %d line.\n\n", line);
    // Open source file and print its contents
    src = fopen(path, "r");
    printFile(src);
    fclose(src);
    return 0;
}
void printFile(FILE *fptr){
    char ch;
    while((ch = fgetc(fptr)) != EOF)
    putchar(ch);
}
void deleteLine(FILE *src, FILE *temp, const int line){
    char buffer[BUFFER_SIZE];
    int count = 1;
    while ((fgets(buffer, BUFFER_SIZE, src)) != NULL){
        if (line != count)
            fputs(buffer, temp);
        count++;
    }
}

실행 결과

위 프로그램을 실행하면 다음과 같은 결과가 출력됩니다.

enter the text.press cntrl Z:
Hi welcome to my world
This is C programming tutorial
You want to learn C programming
Subscribe the course in TutorialsPoint
^Z
Enter file path: cprogramming.txt
Enter line number to remove: 2

File contents before removing line.
Hi welcome to my world
This is C programming tutorial
You want to learn C programming
Subscribe the course in TutorialsPoint

File contents after removing 2 line.

Hi welcome to my world
You want to learn C programming
Subscribe the course in TutorialsPoint

핵심 함수 정리

이 프로그램에서 사용된 주요 표준 라이브러리 함수는 다음과 같습니다.

  • fgets() - 파일에서 한 줄씩 읽어 지정한 버퍼에 저장합니다.
  • fputs() - 버퍼에 담긴 문자열을 파일에 기록합니다.
  • rewind() - 파일 포인터를 파일의 맨 처음 위치로 되돌립니다.
  • remove() - 지정한 경로의 파일을 삭제합니다.
  • rename() - 파일의 이름을 변경합니다.

C 표준 라이브러리에는 파일 중간에 있는 내용을 직접 삭제하는 기능이 제공되지 않기 때문에, 위 예제처럼 임시 파일을 만들어 삭제할 줄을 제외한 나머지 내용을 복사한 뒤 원본 파일을 대체하는 방식이 널리 사용됩니다. 이 방법은 간단하면서도 안전하게 원하는 줄만 제거할 수 있다는 장점이 있습니다.