파일은 디스크의 물리적 저장 위치이고 디렉토리는 파일을 구성하는 데 사용되는 논리적 경로입니다. 디렉토리 내에 파일이 있습니다.
파일에 대해 수행할 수 있는 세 가지 작업은 다음과 같습니다. -
- 파일을 엽니다.
- 파일 처리(읽기, 쓰기, 수정).
- 파일을 저장하고 닫습니다.
알고리즘
파일에서 한 줄을 제거하는 C 프로그램을 설명하는 알고리즘이 아래에 나와 있습니다.
1단계 − 런타임에 제거할 파일 경로와 줄 번호를 읽습니다.
2단계 − 읽기 모드에서 파일을 열고 소스 파일에 저장합니다.
3단계 − 쓰기 모드에서 임시 파일을 생성 및 열고 임시 파일에 해당 참조를 저장합니다.
4단계 − 행 번호를 추적하기 위해 count =1을 초기화합니다.
5단계 − 소스 파일에서 한 줄을 읽어 버퍼에 저장합니다.
6단계 − 현재 라인이 제거할 라인과 같지 않은 경우, 즉 if (line !=count), 버퍼를 임시 파일에 씁니다.
7단계 − 증가 수++.
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