【问题标题】:How to repeatedly read to and from files and erase their contents occasionally?如何反复读取文件并偶尔擦除其内容?
【发布时间】:2014-05-02 19:30:19
【问题描述】:

我有 4 个文件我声明为 fstream、File1、File2、File3、File4;我打开一个包含 120 个整数的单独 data.txt 文件并将其内容读入 file1。然后我必须将 file1 的内容读入一个大小为 20 的数组,对其进行排序,然后将其写入 file3,然后再次执行并写入 file4。所以此时 file3 和 file4 每个都包含 3 个 20 个已排序整数的块,而 file1 仍然包含原始的 120 个整数。现在我必须对 file3 和 file4 进行合并排序,但一次只能有 20 个元素进入内存。到目前为止,一切都运行良好。我的问题是我必须将合并排序内容写回file1和file2。 File1 已经打开,我不能关闭它然后重新打开它,我必须清除 file1 的内容,所以它是一个空文件,然后我才能写回它。这是学校实验室的一部分,但我们的老师告诉我们只用谷歌文件操作。我和其他几个孩子以及计算机实验室的导师似乎无法正常工作。

【问题讨论】:

  • 为什么不能关闭再重新打开?关闭它后,您可以使用 std::ios::trunc 参数重新打开它。

标签: c++ file-io


【解决方案1】:

如果您不需要使用fstream,您可以使用freopen

#include <iostream>
#include <cstdio>

using namespace std;

int main() {
  char filename[] = "file1";
  freopen( filename, "r", stdin ); // File content can be read from stdin

  int array[20];
  for(int i=0; i < 20; ++i) {
    cin >> array[i]; // Reads from the file
  }

  freopen( filename, "w", stdout ); // Changes the access to file to write and clears the file 

  // Perform merge .....
  cout << array[0] << endl; // print only to the file

  // ......
  fclose (stdout);
  return 0;
 }

【讨论】:

    猜你喜欢
    • 2018-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多