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++; } }
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
输出
执行上述程序后,将产生以下结果:
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
广告