首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >反转文件文本

反转文件文本
EN

Stack Overflow用户
提问于 2013-11-18 02:14:51
回答 2查看 4.2K关注 0票数 0

我正在尝试编写一个程序,它使用fgets从预先存在的文件中获取文本,将其颠倒,然后将其写入另一个文件。这是我到目前为止写的代码:

代码语言:javascript
运行
复制
#include <stdio.h>
#include <string.h>

int main()
{
  int c, d;
  FILE *file1, *file2;
  char string [100], *begin, *end, temp;

  file1 = fopen("StartingFile.txt", "rt");
  if (file1 == NULL)
    {
      printf ("Error - Couldn't open file\n");
      return (-1);
    }

  fgets(string, 100, file1);

  fclose (file1);
  begin = string;
  end = begin + strlen(string) - 1;

  while (end > begin)
    {
      temp = *begin;
      *begin = *end;
      *end = temp;

      ++begin;
      --end;
    }  

  file2 = fopen("FinalFile.txt", "wt");
  fprintf (file2, "%s", string);
  fclose (file2);
  printf ("%s\n", string);

  return 0;
}

如果先前存在的文件中的所有文本都在一行中,则可以正常工作,但如果它有多行,则只有第一行被颠倒并写入到新文件中。我认为fgets只能读取一行,所以我认为我将不得不使用循环,但我在实现它时遇到了麻烦。有人能帮我一下吗?提前感谢!

EN

回答 2

Stack Overflow用户

发布于 2013-11-18 02:19:09

要从文件中单独读取每一行,请在while循环中使用fgets,如下所示:

代码语言:javascript
运行
复制
while(fgets(string, sizeof(string), file1) != NULL)
{
...
}
fclose(file1); 

在循环内部,对每一行进行操作以反转它。

票数 0
EN

Stack Overflow用户

发布于 2013-11-18 02:40:00

您的代码中有相当多的逻辑错误。我建议使用其他的f*方法。

如果你想要一个简单的解决方案,打开文件,确定它的长度,创建两个文件大小的缓冲区,用文件的内容填充第一个缓冲区,然后执行一个循环,将相反的内容复制到另一个缓冲区,然后写回那个缓冲区。粗略地看起来像这样:

代码语言:javascript
运行
复制
#include <stdio.h>
#include <string.h>

int main()
{
    FILE *file;

    file = fopen("StartingFile.txt", "rt");
    if (file == NULL)
    {
        printf ("Error - Couldn't open file\n");
        return (-1);
    }

    fseek(file, 0, SEEK_END); // move file pointer to end of file
    long size = ftell(file); // file pointer position == character count in file
    fseek(file, 0, SEEK_SET);  // move back to beginning of file

    char* buffer = malloc(size * sizeof(char));

    fread(buffer, sizeof(char), size, file) // read file contents to buffer

    for(long i = 0; i < size/2; ++i)
    {
        buffer[i] = buffer[size-i-1];
    }

    fseek(file, 0, SEEK_SET); // The fread set the file pointer to the end so we need to put it to the front again.

    fwrite(buffer, sizeof(char), size, file); // Write reverted content

    delete buffer;


    fclose (file);
}

我还没有测试它,它可能包含一些错误,因为我已经有一段时间没有用C语言编程了。无论如何,仍然使用C语言编程的唯一原因是效率,如果你想让你的程序高效,两个缓冲区的解决方案也不是最好的。至少在内存使用方面不是这样。

我强烈建议熟悉C中所有可用的函数(stdio等等),cplusplus.com是一个很好的参考资料。

向您致敬,Xaser

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20034373

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档