ไฟล์เป็นตำแหน่งจัดเก็บจริงบนดิสก์ ไดเรกทอรีเป็นเส้นทางตรรกะจัดระเบียบ
การดำเนินการกับไฟล์ 3 ขั้นตอน: เปิด, ประมวลผล (อ่าน/เขียน/แก้ไข), บันทึกและปิด
อัลกอริทึม
ขั้นตอน 1 - อ่านพาธไฟล์และหมายเลขบรรทัดที่จะลบ
ขั้นตอน 2 - เปิดไฟล์โหมดอ่าน เก็บใน source file
ขั้นตอน 3 - สร้างและเปิด temporary file โหมดเขียน
ขั้นตอน 4 - กำหนด count = 1 ติดตามหมายเลขบรรทัด
ขั้นตอน 5 - อ่านบรรทัดจาก source file เก็บใน buffer
ขั้นตอน 6 - ถ้าบรรทัดปัจจุบัน != บรรทัดที่จะลบ (line != count) เขียน buffer ลง temp file
ขั้นตอน 7 - เพิ่ม count++
ขั้นตอน 8 - ทำซ้ำขั้นตอน 5-7 จนจบ source file
ขั้นตอน 9 - ปิดทั้งสองไฟล์
ขั้นตอน 10 - ลบ source file เดิม
ขั้นตอน 11 - เปลี่ยนชื่อ temp file เป็น source file path
โปรแกรม
โปรแกรม 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