C程式刪除檔案中的某一行
檔案是磁碟上的物理儲存位置,而目錄是用於組織檔案的邏輯路徑。檔案存在於目錄中。
我們可以對檔案執行以下三種操作:
- 開啟檔案。
- 處理檔案(讀取、寫入、修改)。
- 儲存並關閉檔案。
演算法
下面給出一個演算法來解釋如何用C程式刪除檔案中的某一行。
步驟1 - 在執行時讀取檔案路徑和要刪除的行號。
步驟2 - 以讀取模式開啟檔案並將其儲存在原始檔中。
步驟3 - 建立並以寫入模式開啟一個臨時檔案,並將它的引用儲存在臨時檔案中。
步驟4 - 初始化計數器 count = 1 來跟蹤行號。
步驟5 - 從原始檔讀取一行並將其儲存在緩衝區中。
步驟6 - 如果當前行不等於要刪除的行,即 if (line != count),則將緩衝區寫入臨時檔案。
步驟7 - 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:
"); 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.
"); exit(EXIT_FAILURE); } printf("
File contents before removing line.
"); 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("
File contents after removing %d line.
", 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
廣告