How to delete last line in a text file?

前端 未结 6 911
一整个雨季
一整个雨季 2020-12-11 02:30

I have a simple log text file with the extension of .txt with a white space line at the end of that text file every time the log file is generated from a 3rd party program.<

6条回答
  •  我在风中等你
    2020-12-11 03:12

    If you want to delete last N lines from a file without loading all into memory:

    int numLastLinesToIgnore = 10;
    string line = null;
    Queue deferredLines = new Queue();
    using (TextReader inputReader = new StreamReader(inputStream))
    using (TextWriter outputReader = new StreamWriter(outputStream))
    {
        while ((line = inputReader.ReadLine()) != null)
        {
            if (deferredLines.Count() == numLastLinesToIgnore)
            {
                outputReader.WriteLine(deferredLines.Dequeue());
            }
    
            deferredLines.Enqueue(line);
        }
        // At this point, lines still in Queue get lost and won't be written
    }
    

    What happens is that you buffer each new line in a Queue with dimension numLastLinesToIgnore and pop from it a line to write only when Queue is full. You actually read-ahead the file and you are able to stop numLastLinesToIgnore lines before the end of file is reached, without knowing the total number of lines in advance.

    Note that if text has less than numLastLinesToIgnore, result is empty.

    I came up with it as a mirror solution to this: Delete specific line from a text file?

提交回复
热议问题