用c ++写一个循环文件

Kra*_*ram 8 c++ file-io ofstream

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

任何人都有任何想法?

Nol*_*rin 9

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

新建议

我刚刚想到了一种新的方法可能会为你做到这一点......

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

编辑:垃圾,我刚刚描述了一个循环缓冲区的变种!

标题字段

  • Bytes 00 - 07 (long) - 写入文件的总(当前)行数.
  • Bytes 08 - 15 (long) - 指向文件"实际"第一行开头的指针.这最初将是标题结束后的字节,但稍后会在数据被覆盖时更改
  • 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.

我完全承认,这不是一个非常简单的算法!尽管如此,我认为它在某种程度上相当优雅.当然,如果有任何不清楚的地方,请告诉我.希望它应该正是你想要的.

原始建议

现在,如果你的线路保证长度恒定(以字节为单位),你可以很容易地找回合适的点并覆盖现有数据.然而,这似乎是一种不太可能的情况.如果您不介意强制限制您的线条必须具有最大长度,并且另外填充您写入的每条线条的最大长度,那么这对您来说很容易.尽管如此,它还有一些缺点,例如在某些情况下大大增加文件大小(即大多数行都比最大长度短得多).这一切都取决于这种情况是否可以接受......

最后,您可能希望考虑使用现有的日志记录系统,具体取决于您的确切目的.


ang*_*son 7

处理不会大小爆炸的日志记录的常用方法是使用滚动日志文件,每天滚动一次或类似文件,并且只保留N个最新文件.

例如,您每天都会创建一个文件名为"application_2009_05_20.log"的新日志文件,并开始写入,始终附加.

一旦有14天的日志文件,就开始删除最旧的日志文件.


xto*_*ofl 5

由于文件是面向字节的,并且您需要面向行的服务,因此您有两种选择:

  1. 在文件周围实现面向行的包装器

  2. 切换到一些面向线路的设备.我最重要的是:SQLite提供了一些不错的C++包装器.