Thuật toán
- Đọc đường dẫn file và số dòng cần xóa.
- Mở file gốc đọc, tạo file tạm ghi.
- Đọc từng dòng, nếu số dòng khác dòng cần xóa thì ghi vào file tạm.
- Đóng cả hai file, xóa file gốc, đổi tên file tạm thành file gốc.
Chương trình 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, *temp;
char ch, path[100];
int line;
// Tạo file mẫu
src = fopen("cprogramming.txt", "w");
printf("Nhập văn bản (Ctrl+Z kết thúc):\n");
while ((ch = getchar()) != EOF) putc(ch, src);
fclose(src);
printf("Đường dẫn file: "); scanf("%s", path);
printf("Số dòng cần xóa: "); scanf("%d", &line);
src = fopen(path, "r");
temp = fopen("delete.tmp", "w");
if (!src || !temp) { printf("Lỗi mở file.\n"); exit(EXIT_FAILURE); }
printf("\nNội dung trước khi xóa:\n"); printFile(src);
rewind(src);
deleteLine(src, temp, line);
fclose(src); fclose(temp);
remove(path);
rename("delete.tmp", path);
printf("\n\nNội dung sau khi xóa dòng %d:\n\n", line);
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)) {
if (line != count) fputs(buffer, temp);
count++;
}
}
Kết quả
Nhập văn bản... ^Z
Đường dẫn file: cprogramming.txt
Số dòng cần xóa: 2
Nội dung trước khi xóa:
Dòng 1
Dòng 2
Dòng 3
Nội dung sau khi xóa dòng 2:
Dòng 1
Dòng 3