Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Lập Trình C

Chương trình C xóa một dòng khỏi file

Thuật toán

  1. Đọc đường dẫn file và số dòng cần xóa.
  2. Mở file gốc đọc, tạo file tạm ghi.
  3. Đọ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.
  4. Đó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