c - 使用C从文本文件中删除多个字符

标签 c string file

我正在尝试从文本文件中删除特定字符串。我必须从文件 [Ipsum,printing] 中删除两个字符串。我首先尝试从文件中仅删除第一个字符串。但该字符串无法删除。我无法纠正我的代码,因为我犯了错误。

#include <stdio.h>
#include <stdlib.h>
  int main() {
    int j = 0, i;
    char getText[1000] = "Lorem Ipsum is simply dummy text of the printing and typesetting industry";
    FILE * fptr, * fp2;
    char a[1000], temp[1000];

    char key[50] = "Ipsum", textDelete_2[50] = "printing";

    fptr = fopen("D:\\test.txt", "w");
    if (fptr == NULL) {
      printf("File can not be opened. \n");
      exit(0);
    }

    fputs(getText, fptr);

    fp2 = fopen("D:\\temp.txt", "w");
    if (fp2 == NULL) {
      printf("File fp2 can not be opened. \n");
      exit(0);
    }
    printf("\n processing ... \n");

    while (fgets(a,1000,fptr)) {
      for (i = 0; a[i] != '\0'; ++i) {
        if (a[i] == ' ') {
          temp[j] = 0;
          if (strcmp(temp, key) != 0) {
            fputs(temp, fp2);
          }
          j = 0;

          fputs(" ", fp2);
        } else {
          temp[j++] = a[i];
        }
      }

      if (strcmp(temp, key) != 0) {
        fputs(temp, fp2);
      }
      fputs("\n", fp2);
      a[0] = 0;
    }

    fclose(fptr);
    fclose(fp2);
    printf("\n processing completed");
    return 0;
  }

最佳答案

首先,您的输入文件是使用代表write的参数w打开的,因此它将清除输入文件的内容,使输入变得无用。

如果在行尾之前或读取的 1000 个字符之前是\0,您的代码也会生成符号(如果您没有写入整行或 1000 个字符,它将把其余内容作为符号读取)。

最终代码

#include <stdio.h>
#include <stdlib.h>
  int main() {
    int j = 0, i;
    FILE * fptr, * fp2;
    char a[1024], temp[1024];

    char *key = "THIS", *textDelete_2 = "IS";

    fptr = fopen("test.txt", "r");
    if (fptr == NULL) {
      printf("File can not be opened. \n");
      exit(0);
    }

    fp2 = fopen("temp.txt", "w");
    if (fp2 == NULL) {
      printf("File fp2 can not be opened. \n");
      exit(0);
    }
    printf("\n processing ... \n");

    while (fgets(a, sizeof(a), fptr)) {
      for (i = 0; a[i] != '\0'; ++i) {
          if (a[i] == 0)break;
        if (a[i] == ' ') {
          temp[j] = 0;
          if (strcmp(temp, key) != 0) {
            fputs(temp, fp2);
          }
          j = 0;

          fputs(" ", fp2);
        } else {
          temp[j++] = a[i];
        }
      }

      for (i = 0; i < strlen(temp); i++){

          if (!isalpha(temp[i]))temp[i] = ' ';
      }
      if (strcmp(temp, key) != 0) {
        fputs(temp, fp2);
      }
      fputs("\n", fp2);
      a[0] = 0;
    }

    fclose(fptr);
    fclose(fp2);
    printf("\n processing completed");
    getchar();
    return 0;
  }

输入:

THIS IS SPARTAAAAAAAAAAAAAA 

输出:

 IS SPARTAAAAAAAAAAAAAA  

关于c - 使用C从文本文件中删除多个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43436605/

相关文章:

c char ** 导致分配错误

C 编程-从 char * 转换为 char 数组?

Python 删除非拉丁字符

java - 读取数据以从文本文件加载游戏

c - 格式 ‘%d’ 需要类型为 ‘int’ 的参数,但参数 2 的类型为 ‘int *’

c - 将可变数量的参数传递给 C 函数

r - 检查非唯一字符的字符串模式

c++ - 获取 Cstrings 的控制台输入

Linux (Ubuntu 9.04) 权限 - 如何删除 rws?

file - Rust:如何从文件中读取十六进制