Home > Enterprise >  How to always have N number of lines in a ofstream file with real-time data
How to always have N number of lines in a ofstream file with real-time data

Time:10-15

I'd like to write lines to a file using ofstream, 10 times, and I want the 11th line to be written in the 1st line's place, 12th in 2nd, and so on (so that my file would always have 10 lines, to preserve log file size). So far my best try involves a circular buffer, shown below:

#include <cstdio>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
​
int main()
{
    ifstream myfile("new.txt");
    string line, buffer[10];
    const size_t size = sizeof buffer / sizeof * buffer;
    size_t i = 0;
​
    while (getline(myfile, line))
    {
        buffer[i] = line;
        if (  i >= size)
        {
            i = 0;
        }
    }
​
    ofstream myfileo("new.txt");
    for (size_t j = 0; j < size;   j)
    {
        myfileo << buffer[i] << "\n";
        if (  i >= size)
        {
            i = 0;
        }
    }
    myfileo << "hey";
    return 0;
}

But this tends to only work on VS windows and not on the actual c code run on linux with real-time data (silly, I know). The "real-time data" part is that myfileo << "hey" line.

Should it really be this difficult to have a log file with only 10 lines in C ?! I think another good try would be creating new log files after a certain amount of lines reached and deleting the previous ones, but I don't know how I could write that! Thanks

CodePudding user response:

You can sort-of get the behavior you want by doing a

 myfileo.seekp(0, std::ios_base::beg);

... every time you've just finished writing out the tenth line of text. That will move the file's write-position back to the top of the file, and from there on you'll be overwriting existing contents of the file instead of making the file larger.

I say "sort of", because unless all of your text-lines are exactly the same length, then you're going to end up with some leftover bytes at the end of the file whenever the previous 10 lines were longer than the new 10 lines. Maybe that's acceptable for your purpose, I don't know.

Another possible approach would be to myfileo.close() your ofstream after 10 lines and myfileo.open() a new file with a different name, and start writing to that file instead. Then when the new file is "full", delete the older file, and repeat the process. That way you'd always have two files on disk, one complete 10-line "old" file and a smaller (<10-line) "in progress" file; the advantage is that both files would be well-formed at all times.

  • Related