繁体   English   中英

如何修改代码以接受字符串作为用户输入并使用 strcmp 与文本文件的内容进行比较然后删除该行?

[英]How can I modify the code to accept string as user input and use strcmp to compare with the contents of the text file then delete that line?

嘿,我有一个问题,如果假设我想输入一个字符串以与文本文件进行比较,并且如果该单词匹配,那么我想删除包含该字符串的那一行...如何修改下面的代码,因为下面的代码将行号作为输入来删除特定的行。 谢谢..

#include <stdio.h>
    
    int main()
    {
    FILE *fileptr1, *fileptr2;
    char filename[40];
    char ch;
    int delete_line, temp = 1;

    printf("Enter file name: ");
    scanf("%s", filename);
    //open file in read mode
    fileptr1 = fopen(filename, "r");
    ch = getc(fileptr1);
   while (ch != EOF)
    {
        printf("%c", ch);
        ch = getc(fileptr1);
    }
    //rewind
    rewind(fileptr1);
    printf(" \n Enter line number of the line to be deleted:");
    scanf("%d", &delete_line);
    //open new file in write mode
    fileptr2 = fopen("replica.c", "w");
    ch = 'A';
    while (ch != EOF)
    {
        ch = getc(fileptr1);
        //except the line to be deleted
        if (temp != delete_line)
        {
            //copy all lines in file replica.c
            putc(ch, fileptr2);
        }
        if (ch == '\n')
        {
            temp++;
        }
    }
    fclose(fileptr1);
    fclose(fileptr2);
    remove(filename);
    //rename the file replica.c to original name
    rename("replica.c", filename);
    printf("\n The contents of file after being modified are as follows:\n");
    fileptr1 = fopen(filename, "r");
    ch = getc(fileptr1);
    while (ch != EOF)
    {
        printf("%c", ch);
        ch = getc(fileptr1);
    }
    fclose(fileptr1);
    return 0;
}

文本文件内容示例:

 hello world up
 one two three

我对编译器的输入:你好

屏幕上的 Output:

one two three

检测匹配

在打印文件的初始循环中,添加行比较检测。

一些未经测试的代码给 OP 一个想法。

// We are looking for a needle in a haystack
const char *needle = "Hello World\n";  // must end with \n
// ...
delete_line = -1;
size_t needle_column = 0;
int line = 0;

while (ch != EOF) {
  printf("%c", ch);
  // If still looking for the line and within a line ...
  if (delete_line == -1 && needle_column != SIZE_MAX) {
    if (ch == needle[needle_column]) {
      needle_column++; 
      if (needle[needle_column] == '\0') {
        delete_line = line; // Found it!
      }
    } else {
      needle_column = SIZE_MAX; // Do not compare rest of line
    }
  }

  if (ch == '\n') {
    line++;
    needle_column = 0; 
  }

  ch = getc(fileptr1);
}

if (delete_line == -1) {
  printf("Line not found\n");
}

下一步

  • 修改为不要求needle'\n'结尾。 然后还要调整代码以允许最后一行可能不包含'\n'的匹配。

  • 使用int ch而不是char ch来正确处理来自fgetc()的 257 个不同结果。 needle调整为const unsigned char *

  • 为了支持文件,请考虑一种比int更宽的行数类型,例如long long

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM