C程序从文件中删除一行

文件是磁盘上的物理存储位置,目录是用于组织文件的逻辑路径。文件存在于目录中。

我们可以对文件执行的三个操作如下 -

  • 打开一个文件。

  • 处理文件(读、写、修改)。

  • 保存并关闭文件。

算法

下面给出了一个算法来解释从文件中删除一行的 C 程序。

步骤 1 - 读取文件路径和行号以在运行时删除。

步骤 2 - 以读取模式打开文件并存储在源文件中。

步骤 3 - 在写入模式下创建并打开一个临时文件,并将其引用存储在临时文件中。

步骤 4 - 初始化计数 = 1 以跟踪行号。

步骤 5 - 从源文件中读取一行并将其存储在缓冲区中。

步骤 6 - 如果当前行不等于要删除的行,即如果(行!= 计数),则将缓冲区写入临时文件。

步骤 7 - 增加计数++。

步骤 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 thetext.presscntrl Z:\n");

   while((ch = getchar())!=EOF){

      putc(ch,src);

   }

   fclose(src);

   printf("输入文件路径: ");

   scanf("%s", path);

   printf("输入要删除的行号: ");

   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);

   // 将 src 文件指针移到开头

   rewind(src);

   // 从文件中删除给定的行。

   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);

   // 打开源文件并打印其内容

   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 thetext.presscntrl Z:

Hi welcome to my world

This is C programming tutorial

You want to learn C programming

Subscribe the course in nhooo

^Z

输入文件路径: cprogramming.txt

输入要删除的行号: 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 nhooo

File contents after removing 2 line.

Hi welcome to my world

You want to learn C programming

Subscribe the course in nhooo

以上是 C程序从文件中删除一行 的全部内容, 来源链接: utcz.com/z/341337.html

回到顶部