ANSI C - 文本文件:修改行? [英] ANSI C - Text File: Modify Line?

查看:28
本文介绍了ANSI C - 文本文件:修改行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个文本文件:

Line 1. "house"
Line 2. "dog"
Line 3. "mouse"
Line 4. "car"
...

我想改变第 2 行.狗"在新的第 2 行.卡片"

I want to change Line 2. "dog" in new Line 2."cards"

我该怎么办?

谢谢!

(抱歉我的英语不好)

推荐答案

你的程序可能是这样的:

Your program could like this:

#include <stdio.h>
#include <stdlib.h>

#define MAX_LINE_LENGTH 1000

int main()
{
  FILE * fp_src, *fp_dest;
  char line[MAX_LINE_LENGTH];

  fp_src = fopen("PATH_TO_FILE\test.txt", "r"); // This is the file to change
  if (fp_src == NULL)
    exit(EXIT_FAILURE);

  fp_dest = fopen("PATH_TO_FILE\test.txt_temp", "w"); // This file will be created
  if (fp_dest == NULL)
    exit(EXIT_FAILURE);


  while (fgets(line, 1000, fp_src) != NULL) {

    if (strncmp(line, "Line 2.", 7) == 0) {
      fputs("Line 2. "cards"
", fp_dest);
      printf("Applied new content: %s", "Line 2. "cards"
");
    }
    else {
      fputs(line, fp_dest);
      printf("Took original line: %s", line);
    }

  }

  fclose(fp_src);
  fclose(fp_dest);

  unlink("PATH_TO_FILE\test.txt");
  rename("PATH_TO_FILE\test.txt_temp", "PATH_TO_FILE\test.txt");

  exit(EXIT_SUCCESS);
}

将此解决方案应用于某些生产系统时应考虑以下事项:

The following things you should consider when taking this solution into some production system:

  • 1000 的最大行长度是否满足您的需求 - 也许您想提出一种使用 malloc() 为一行动态分配内存的解决方案
  • 您应该使用一些随机文件名生成器来生成临时文件并确保它尚不存在,因此您不会覆盖现有文件
  • 对于大文件,这种方法可能不是最好的,因为您的文件内容实际上在内存中存储了两次
  • Does the maximum line length of 1000 staisfy your needs - maybe you want to come up with a solution that uses malloc() to dynamically allocate memory for one line
  • You should take some random-filename-generator to generate the temporary file and make sure that it doesn't exist yet, so you don't overwrite an existing file
  • With large files this approach is maybe not the best because you effectivly have your file-content twice in memory

这篇关于ANSI C - 文本文件:修改行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆