c++ - 用c++写一个循环文件

标签 c++ file-io ofstream

我需要用c++写一个循环文件​​。程序必须在文件中写入行,当代码达到最大行数时,它必须覆盖文件开头的行。

有人知道吗?

最佳答案

不幸的是,您不能在不重写整个文件的情况下截断/覆盖文件开头的行。

新建议

我刚刚想到了一种可能对您有用的新方法...

您可以在具有以下结构的文件中包含一个小标题。

编辑: 废话,我刚刚描述了一个 circular buffer 的变体!

标题字段

  • 字节 00 - 07(长) - 写入文件的总(当前)行数。
  • Bytes 08 - 15 (long) - 指向文件“实际”第一行开头的指针。这最初是 header 结束后的字节,但稍后会在数据被覆盖时更改。`
  • Bytes 16 - 23 (long) - 文件“结束部分”的长度。同样,这最初将为零,但稍后会在数据被覆盖时发生变化。

读取算法(伪代码)

读取整个文件。

Read the header field that points to the start of the "actual" first line
Read the header field that specifies the length of the "end section"
Read every line until the end of the file
Seek to the byte just after the end of the header
Read every line until the "end section" has been fully read

编写算法(伪代码)

向文件写入任意数量的新行。

Read the header field that contains the total no. of lines in the file
If (line count) + (no. of new lines) <= (maximum no. of lines) Then
    Append new lines to end of file
    Increment header field for line count by (no. of ne lines)
Else
    Append as many lines as possible (up to maximum) to end of file
    Beginning at pointer to first line (in header field), read as many lines as still need to be written
    Find the total byte count of the lines just read
    Set the header field that points to the first line to the next byte in the stream
    Keep writing the new lines to the end of the file, each at a time, until the byte count of the remaining lines is less than the byte count of the lines at the beginning of the file (it may be that this condition is true immediately, in which case you don't need to write any more)
    Write the remaining new lines to the start of the file (starting at the byte after the header)
    Set the header field that contains the length of the "end section" of the file to the number of bytes just written after the header.

这不是一个非常简单的算法,我完全承认!尽管如此,我还是认为它在某种程度上非常优雅。当然,如果有任何不清楚的地方,请告诉我。希望它现在能准确地执行您想要的操作。

原始建议

现在,如果保证行的长度恒定(以字节为单位),您可以很容易地返回到适当的点并覆盖现有数据。然而,这似乎不太可能发生。如果您不介意施加限制,即您的行必须具有最大长度,并且另外将您写入的每一行填充到这个最大长度,那么这对您来说可能会很容易。尽管如此,它也有其缺点,例如在某些情况下会大大增加文件大小(即大多数行比最大长度短得多。)这是否可以接受完全取决于情况......

最后,您可能想要考虑利用现有的日志系统,具体取决于您的具体目的。

关于c++ - 用c++写一个循环文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/887689/

相关文章:

C++自动更新程序

c++ - 如何对在测试对象中创建的模拟对象做出期望?

c++ - 为什么无法识别我重载的乘法运算符?

c++ - 如何: return multidimensional vector (Matrix) from function - using header

ios - AS3 将 SWF 保存到 iOS 设备,然后将其加载回 MovieClip

java - Android AudioData追加到结束

c++ - 我应该从 main() 返回 EXIT_SUCCESS 还是 0?

java - 如何将txt文件中的数据复制到数组

c++ - 是否可以将 cout 或 fout 传递给函数?

c++ - ofstream::open() 上的段错误如果在函数外部定义