C # में पुनरावृत्ति के साथ एक पाठ फ़ाइल कैसे पढ़ें


87

मुझे एक बड़ी फ़ाइल संसाधित करने की आवश्यकता है, लगभग 400K लाइनें और 200 M। लेकिन कभी-कभी मुझे नीचे से ऊपर की प्रक्रिया करनी होती है। मैं इटरेटर (उपज वापसी) का उपयोग कैसे कर सकता हूं? मूल रूप से मुझे हर चीज को मेमोरी में लोड करना पसंद नहीं है। मुझे पता है कि .NET में इट्रेटर का उपयोग करना अधिक कुशल है।



एक संभावना यह होगी कि अंत से पर्याप्त मात्रा में एक बड़ी मात्रा में पढ़ा जाए और फिर String.LastIndexOf का उपयोग करके "\ r \ n" के लिए पीछे की ओर जाएं।
— user34660

दो प्रतियों में मेरी टिप्पणी देखें stackoverflow.com/questions/398378/...
— Xan-कुन क्लार्क डेविस

जवाबों:


136

जब तक आप निश्चित आकार के एन्कोडिंग (जैसे ASCII) का उपयोग नहीं कर रहे हैं, तब तक पीछे की ओर पाठ फ़ाइलों को पढ़ना बहुत मुश्किल है। जब आपको वैरिएबल-साइज़ एन्कोडिंग मिली हो (जैसे कि UTF-8) तो आप जाँचते रहेंगे कि आप किसी पात्र के बीच में हैं या नहीं जब आप डेटा ला रहे हों।

ढांचे में कुछ भी नहीं बनाया गया है, और मुझे संदेह है कि आपको प्रत्येक चर-चौड़ाई एन्कोडिंग के लिए अलग-अलग हार्ड कोडिंग करनी होगी।

संपादित करें: यह कुछ हद तक परीक्षण किया गया है - लेकिन यह कहना नहीं है कि यह अभी भी आसपास कुछ सूक्ष्म कीड़े नहीं है। यह MiscUtil से StreamUtil का उपयोग करता है, लेकिन मैंने नीचे से बस आवश्यक (नया) तरीका शामिल किया है। ओह, और इसे फिर से तैयार करने की आवश्यकता है - जैसा कि आप देखेंगे, एक सुंदर विधि है:

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace MiscUtil.IO
{
    /// <summary>
    /// Takes an encoding (defaulting to UTF-8) and a function which produces a seekable stream
    /// (or a filename for convenience) and yields lines from the end of the stream backwards.
    /// Only single byte encodings, and UTF-8 and Unicode, are supported. The stream
    /// returned by the function must be seekable.
    /// </summary>
    public sealed class ReverseLineReader : IEnumerable<string>
    {
        /// <summary>
        /// Buffer size to use by default. Classes with internal access can specify
        /// a different buffer size - this is useful for testing.
        /// </summary>
        private const int DefaultBufferSize = 4096;

        /// <summary>
        /// Means of creating a Stream to read from.
        /// </summary>
        private readonly Func<Stream> streamSource;

        /// <summary>
        /// Encoding to use when converting bytes to text
        /// </summary>
        private readonly Encoding encoding;

        /// <summary>
        /// Size of buffer (in bytes) to read each time we read from the
        /// stream. This must be at least as big as the maximum number of
        /// bytes for a single character.
        /// </summary>
        private readonly int bufferSize;

        /// <summary>
        /// Function which, when given a position within a file and a byte, states whether
        /// or not the byte represents the start of a character.
        /// </summary>
        private Func<long,byte,bool> characterStartDetector;

        /// <summary>
        /// Creates a LineReader from a stream source. The delegate is only
        /// called when the enumerator is fetched. UTF-8 is used to decode
        /// the stream into text.
        /// </summary>
        /// <param name="streamSource">Data source</param>
        public ReverseLineReader(Func<Stream> streamSource)
            : this(streamSource, Encoding.UTF8)
        {
        }

        /// <summary>
        /// Creates a LineReader from a filename. The file is only opened
        /// (or even checked for existence) when the enumerator is fetched.
        /// UTF8 is used to decode the file into text.
        /// </summary>
        /// <param name="filename">File to read from</param>
        public ReverseLineReader(string filename)
            : this(filename, Encoding.UTF8)
        {
        }

        /// <summary>
        /// Creates a LineReader from a filename. The file is only opened
        /// (or even checked for existence) when the enumerator is fetched.
        /// </summary>
        /// <param name="filename">File to read from</param>
        /// <param name="encoding">Encoding to use to decode the file into text</param>
        public ReverseLineReader(string filename, Encoding encoding)
            : this(() => File.OpenRead(filename), encoding)
        {
        }

        /// <summary>
        /// Creates a LineReader from a stream source. The delegate is only
        /// called when the enumerator is fetched.
        /// </summary>
        /// <param name="streamSource">Data source</param>
        /// <param name="encoding">Encoding to use to decode the stream into text</param>
        public ReverseLineReader(Func<Stream> streamSource, Encoding encoding)
            : this(streamSource, encoding, DefaultBufferSize)
        {
        }

        internal ReverseLineReader(Func<Stream> streamSource, Encoding encoding, int bufferSize)
        {
            this.streamSource = streamSource;
            this.encoding = encoding;
            this.bufferSize = bufferSize;
            if (encoding.IsSingleByte)
            {
                // For a single byte encoding, every byte is the start (and end) of a character
                characterStartDetector = (pos, data) => true;
            }
            else if (encoding is UnicodeEncoding)
            {
                // For UTF-16, even-numbered positions are the start of a character.
                // TODO: This assumes no surrogate pairs. More work required
                // to handle that.
                characterStartDetector = (pos, data) => (pos & 1) == 0;
            }
            else if (encoding is UTF8Encoding)
            {
                // For UTF-8, bytes with the top bit clear or the second bit set are the start of a character
                // See http://www.cl.cam.ac.uk/~mgk25/unicode.html
                characterStartDetector = (pos, data) => (data & 0x80) == 0 || (data & 0x40) != 0;
            }
            else
            {
                throw new ArgumentException("Only single byte, UTF-8 and Unicode encodings are permitted");
            }
        }

        /// <summary>
        /// Returns the enumerator reading strings backwards. If this method discovers that
        /// the returned stream is either unreadable or unseekable, a NotSupportedException is thrown.
        /// </summary>
        public IEnumerator<string> GetEnumerator()
        {
            Stream stream = streamSource();
            if (!stream.CanSeek)
            {
                stream.Dispose();
                throw new NotSupportedException("Unable to seek within stream");
            }
            if (!stream.CanRead)
            {
                stream.Dispose();
                throw new NotSupportedException("Unable to read within stream");
            }
            return GetEnumeratorImpl(stream);
        }

        private IEnumerator<string> GetEnumeratorImpl(Stream stream)
        {
            try
            {
                long position = stream.Length;

                if (encoding is UnicodeEncoding && (position & 1) != 0)
                {
                    throw new InvalidDataException("UTF-16 encoding provided, but stream has odd length.");
                }

                // Allow up to two bytes for data from the start of the previous
                // read which didn't quite make it as full characters
                byte[] buffer = new byte[bufferSize + 2];
                char[] charBuffer = new char[encoding.GetMaxCharCount(buffer.Length)];
                int leftOverData = 0;
                String previousEnd = null;
                // TextReader doesn't return an empty string if there's line break at the end
                // of the data. Therefore we don't return an empty string if it's our *first*
                // return.
                bool firstYield = true;

                // A line-feed at the start of the previous buffer means we need to swallow
                // the carriage-return at the end of this buffer - hence this needs declaring
                // way up here!
                bool swallowCarriageReturn = false;

                while (position > 0)
                {
                    int bytesToRead = Math.Min(position > int.MaxValue ? bufferSize : (int)position, bufferSize);

                    position -= bytesToRead;
                    stream.Position = position;
                    StreamUtil.ReadExactly(stream, buffer, bytesToRead);
                    // If we haven't read a full buffer, but we had bytes left
                    // over from before, copy them to the end of the buffer
                    if (leftOverData > 0 && bytesToRead != bufferSize)
                    {
                        // Buffer.BlockCopy doesn't document its behaviour with respect
                        // to overlapping data: we *might* just have read 7 bytes instead of
                        // 8, and have two bytes to copy...
                        Array.Copy(buffer, bufferSize, buffer, bytesToRead, leftOverData);
                    }
                    // We've now *effectively* read this much data.
                    bytesToRead += leftOverData;

                    int firstCharPosition = 0;
                    while (!characterStartDetector(position + firstCharPosition, buffer[firstCharPosition]))
                    {
                        firstCharPosition++;
                        // Bad UTF-8 sequences could trigger this. For UTF-8 we should always
                        // see a valid character start in every 3 bytes, and if this is the start of the file
                        // so we've done a short read, we should have the character start
                        // somewhere in the usable buffer.
                        if (firstCharPosition == 3 || firstCharPosition == bytesToRead)
                        {
                            throw new InvalidDataException("Invalid UTF-8 data");
                        }
                    }
                    leftOverData = firstCharPosition;

                    int charsRead = encoding.GetChars(buffer, firstCharPosition, bytesToRead - firstCharPosition, charBuffer, 0);
                    int endExclusive = charsRead;

                    for (int i = charsRead - 1; i >= 0; i--)
                    {
                        char lookingAt = charBuffer[i];
                        if (swallowCarriageReturn)
                        {
                            swallowCarriageReturn = false;
                            if (lookingAt == '\r')
                            {
                                endExclusive--;
                                continue;
                            }
                        }
                        // Anything non-line-breaking, just keep looking backwards
                        if (lookingAt != '\n' && lookingAt != '\r')
                        {
                            continue;
                        }
                        // End of CRLF? Swallow the preceding CR
                        if (lookingAt == '\n')
                        {
                            swallowCarriageReturn = true;
                        }
                        int start = i + 1;
                        string bufferContents = new string(charBuffer, start, endExclusive - start);
                        endExclusive = i;
                        string stringToYield = previousEnd == null ? bufferContents : bufferContents + previousEnd;
                        if (!firstYield || stringToYield.Length != 0)
                        {
                            yield return stringToYield;
                        }
                        firstYield = false;
                        previousEnd = null;
                    }

                    previousEnd = endExclusive == 0 ? null : (new string(charBuffer, 0, endExclusive) + previousEnd);

                    // If we didn't decode the start of the array, put it at the end for next time
                    if (leftOverData != 0)
                    {
                        Buffer.BlockCopy(buffer, 0, buffer, bufferSize, leftOverData);
                    }
                }
                if (leftOverData != 0)
                {
                    // At the start of the final buffer, we had the end of another character.
                    throw new InvalidDataException("Invalid UTF-8 data at start of stream");
                }
                if (firstYield && string.IsNullOrEmpty(previousEnd))
                {
                    yield break;
                }
                yield return previousEnd ?? "";
            }
            finally
            {
                stream.Dispose();
            }
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }
}


// StreamUtil.cs:
public static class StreamUtil
{
    public static void ReadExactly(Stream input, byte[] buffer, int bytesToRead)
    {
        int index = 0;
        while (index < bytesToRead)
        {
            int read = input.Read(buffer, index, bytesToRead - index);
            if (read == 0)
            {
                throw new EndOfStreamException
                    (String.Format("End of stream reached with {0} byte{1} left to read.",
                                   bytesToRead - index,
                                   bytesToRead - index == 1 ? "s" : ""));
            }
            index += read;
        }
    }
}

प्रतिक्रिया बहुत स्वागत है। यह मजेदार था :)


राइटो - मैं लगभग एक घंटे में शुरू करने की योजना बना रहा हूं। मुझे एकल-बाइट एन्कोडिंग, एनकोडिंग.उनोड, और एनकोडिंग.UTF8 का समर्थन करने में सक्षम होना चाहिए। अन्य डोबुले-बाइट एन्कोडिंग का समर्थन नहीं किया जाएगा। मुझे उम्मीद है कि परीक्षण में दर्द होगा :(
— जॉन स्कीट

4
वाह! मुझे पता है कि यह तीन साल से अधिक पुराना है, लेकिन कोड चट्टानों का यह टुकड़ा! धन्यवाद!! (ps मैं सिर्फ File.OpenRead (File.Open (फ़ाइल नाम, FileMode.Open, FileAccess.Read, FileShare.ReadWrite साथ फ़ाइल का नाम)) इटरेटर पहले से ही खोला फ़ाइलों को पढ़ने जाने के लिए बदल
— Stefano

1
@GrimaceofDespair: अधिक "क्योंकि तब मुझे वंशानुक्रम के लिए डिज़ाइन करना पड़ता था, जो डिज़ाइन समय और भविष्य के लचीलेपन दोनों के संदर्भ में बहुत महत्वपूर्ण लागत जोड़ता है"। अक्सर यह भी स्पष्ट नहीं होता है कि अनुवांशिकता को किस प्रकार से समझदारी से इस्तेमाल किया जा सकता है - इसे स्पष्ट करने के लिए बेहतर है जब तक कि स्पष्टता नहीं मिली है, आईएमओ।
— जॉन स्कीट

3
@ इब्राहिलानशर्मा: जहाँ मुझे समस्याओं को रूढ़िवादी पहलुओं में विभाजित करना पसंद है। आपके द्वारा अपने मामले में फ़ाइल खोलने का तरीका जानने के बाद, मुझे उम्मीद है कि मेरा कोड आपके लिए काम करेगा।
— जॉन स्कीट

1
यदि कोई फ़ाइल को किसी अन्य प्रक्रिया के साथ साझा करने में सक्षम होना चाहता है, जैसे कि जब आप एक लॉग फ़ाइल पढ़ना चाहते हैं, जो कि माता-पिता द्वारा लिखने के लिए खुली हो, तो बस बदलें: File.OpenRead (फ़ाइल नाम) साथ: नया FileStream (फ़ाइल नाम, FileMode)। ओपन, FileAccess.ReadWrite, FileShare.ReadWrite)
— गेमट

9

ध्यान दें: यह दृष्टिकोण काम नहीं करता है (EDIT में समझाया गया है)

आप लाइनों का उपयोग करने के लिए File.ReadLines का उपयोग कर सकते हैं

foreach (var line in File.ReadLines(@"C:\temp\ReverseRead.txt").Reverse())
{
    if (noNeedToReadFurther)
        break;

    // process line here
    Console.WriteLine(line);
}

संपादित करें:

Applejacks01 की टिप्पणी पढ़ने के बाद , मैं कुछ परीक्षण चलाता हूं और ऐसा लगता है कि .Reverse() वास्तव में पूरी फाइल लोड होती है।

मैं एक 40MB फ़ाइल की पहली पंक्तिFile.ReadLines() प्रिंट करता था - कंसोल ऐप का मेमोरी उपयोग 5 एमबी था । फिर, उसी फ़ाइल की अंतिम पंक्तिFile.ReadLines().Reverse() को प्रिंट करने के लिए उपयोग किया जाता है - मेमोरी उपयोग 95 एमबी था ।

निष्कर्ष

जो भी `रिवर्स ()’ कर रहा है, वह एक बड़ी फ़ाइल के नीचे पढ़ने के लिए एक अच्छा विकल्प नहीं है ।


3
मुझे आश्चर्य है कि क्या वास्तव में पूरी फ़ाइल को मेमोरी में रिवर्स करने के लिए कॉल लोड होता है। क्या एनुमरबल के अंतिम बिंदु को पहले स्थापित करने की आवश्यकता नहीं होगी? आंतरिक रूप से, एन्यूमरेबल पूरी तरह से फाइल को
— टेम्परेरी एरे बनाने के लिए एनुमरेट

2
मूल उत्तर गलत था, लेकिन मैं यहां पर EDIDE उत्तर रखता हूं क्योंकि यह अन्य लोगों को इस दृष्टिकोण का उपयोग करने से रोक सकता है।
— रोमन गुडकोव

3

एक फ़ाइल पुनरावृत्ति बनाने के लिए आप यह कर सकते हैं:

संपादित करें:

यह एक निश्चित-चौड़ाई वाली रिवर्स फाइल रीडर का मेरा निश्चित संस्करण है:

public static IEnumerable<string> readFile()
{
    using (FileStream reader = new FileStream(@"c:\test.txt",FileMode.Open,FileAccess.Read))
    {
        int i=0;
        StringBuilder lineBuffer = new StringBuilder();
        int byteRead;
        while (-i < reader.Length)
        {
            reader.Seek(--i, SeekOrigin.End);
            byteRead = reader.ReadByte();
            if (byteRead == 10 && lineBuffer.Length > 0)
            {
                yield return Reverse(lineBuffer.ToString());
                lineBuffer.Remove(0, lineBuffer.Length);
            }
            lineBuffer.Append((char)byteRead);
        }
        yield return Reverse(lineBuffer.ToString());
        reader.Close();
    }
}

public static string Reverse(string str)
{
    char[] arr = new char[str.Length];
    for (int i = 0; i < str.Length; i++)
        arr[i] = str[str.Length - 1 - i];
    return new string(arr);
}

यह अब ISO-8859-1 के लिए सही होने के करीब है, लेकिन किसी अन्य एन्कोडिंग के लिए नहीं। एनकोडिंग वास्तव में इसे मुश्किल बनाते हैं :(
— जॉन स्कीट

"ISO-8859-1 के लिए सही होने के करीब" से आपका क्या मतलब है? अब भी क्या गायब है?
— इगोर ज़ेलया

हैंडलिंग "\ r" "\ n" और "\ r \ n" से मेल खाने के लिए बिल्कुल सही नहीं है, जहां बाद वाला केवल एक पंक्ति के ब्रेक के रूप में गिना जाता है।
— जॉन स्कीट

1
यह कभी भी खाली लाइनें नहीं देता है - "a \ n \ n" को "a", "", "b"
— जॉन स्कीट

mmmmmm ... मुझे लाइनबफ़र तभी मिल रहा है जब मुझे एक '\ n' (ASCII 10) मिलेगा। आप सही कह रहे हैं, मैं 'आर' की प्रशंसा नहीं कर रहा हूँ।
— इगोर ज़ेलया

2

मैंने फ़ाइल को लाइन द्वारा सूची सूची में रखा, फिर List.Reverse () का उपयोग किया;

        StreamReader objReader = new StreamReader(filename);
        string sLine = "";
        ArrayList arrText = new ArrayList();

        while (sLine != null)
        {
            sLine = objReader.ReadLine();
            if (sLine != null)
                arrText.Add(sLine);
        }
        objReader.Close();


        arrText.Reverse();

        foreach (string sOutput in arrText)
        {

...


4
बड़ी फ़ाइलों के लिए सबसे अच्छा समाधान नहीं है क्योंकि आपको इसे पूरी तरह से रैम में लोड करने की आवश्यकता है। और ओपी ने स्पष्ट रूप से निर्दिष्ट किया कि वह इसे पूरी तरह से लोड नहीं करना चाहता है।
— कोडइंचौस

1

आप एक समय में फ़ाइल एक चरित्र को पीछे की ओर पढ़ सकते हैं और सभी पात्रों को तब तक कैश कर सकते हैं जब तक कि आप एक गाड़ी वापसी और / या लाइन फीड तक नहीं पहुंचते।

आप फिर एकत्रित स्ट्रिंग को उल्टा करते हैं और इसे एक पंक्ति के रूप में येल्ड करते हैं।


4
एक समय में एक फ़ाइल एक चरित्र को पीछे की ओर पढ़ना कठिन है - क्योंकि आप एक चरित्र की शुरुआत को पहचानने में सक्षम हो गए हैं। कितना सरल है जो एन्कोडिंग पर निर्भर करेगा।
— जॉन स्कीट

1

मुझे पता है कि यह पोस्ट बहुत पुरानी है, लेकिन जैसा कि मुझे पता नहीं चल पाया कि सबसे अधिक वोट किए गए समाधान का उपयोग कैसे किया जा सकता है, मैंने आखिरकार यह पाया: यहां वीबी और सी # में कम मेमोरी लागत के साथ सबसे अच्छा जवाब मिला।

http://www.blakepell.com/2010-11-29-backward-file-reader-vb-csharp-source

आशा है, मैं इसके साथ दूसरों की मदद करूंगा क्योंकि इस पोस्ट को खोजने में मुझे घंटों लग गए!

[संपादित करें]

यहाँ सी # कोड है:

//*********************************************************************************************************************************
//
//             Class:  BackwardReader
//      Initial Date:  11/29/2010
//     Last Modified:  11/29/2010
//     Programmer(s):  Original C# Source - the_real_herminator
//                     http://social.msdn.microsoft.com/forums/en-US/csharpgeneral/thread/9acdde1a-03cd-4018-9f87-6e201d8f5d09
//                     VB Converstion - Blake Pell
//
//*********************************************************************************************************************************

using System.Text;
using System.IO;
public class BackwardReader
{
    private string path;
    private FileStream fs = null;
    public BackwardReader(string path)
    {
        this.path = path;
        fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
        fs.Seek(0, SeekOrigin.End);
    }
    public string Readline()
    {
        byte[] line;
        byte[] text = new byte[1];
        long position = 0;
        int count;
        fs.Seek(0, SeekOrigin.Current);
        position = fs.Position;
        //do we have trailing rn?
        if (fs.Length > 1)
        {
            byte[] vagnretur = new byte[2];
            fs.Seek(-2, SeekOrigin.Current);
            fs.Read(vagnretur, 0, 2);
            if (ASCIIEncoding.ASCII.GetString(vagnretur).Equals("rn"))
            {
                //move it back
                fs.Seek(-2, SeekOrigin.Current);
                position = fs.Position;
            }
        }
        while (fs.Position > 0)
        {
            text.Initialize();
            //read one char
            fs.Read(text, 0, 1);
            string asciiText = ASCIIEncoding.ASCII.GetString(text);
            //moveback to the charachter before
            fs.Seek(-2, SeekOrigin.Current);
            if (asciiText.Equals("n"))
            {
                fs.Read(text, 0, 1);
                asciiText = ASCIIEncoding.ASCII.GetString(text);
                if (asciiText.Equals("r"))
                {
                    fs.Seek(1, SeekOrigin.Current);
                    break;
                }
            }
        }
        count = int.Parse((position - fs.Position).ToString());
        line = new byte[count];
        fs.Read(line, 0, count);
        fs.Seek(-count, SeekOrigin.Current);
        return ASCIIEncoding.ASCII.GetString(line);
    }
    public bool SOF
    {
        get
        {
            return fs.Position == 0;
        }
    }
    public void Close()
    {
        fs.Close();
    }
}

आपको अपने उत्तर में लिंक से संबंधित भागों को शामिल करना चाहिए और केवल संदर्भ के लिए लिंक जोड़ना चाहिए, ताकि लिंक बदलने पर भी आपका जवाब मूल्य में इजाफा हो।
— थॉमस फ्लिन्को 19

यदि आपके पास निजी IDisposableक्षेत्र हैं, तो आपको IDisposableभी लागू करना चाहिए , और इन क्षेत्रों का उचित निपटान करना चाहिए ।
— थोमसब

1

विशाल फ़ाइलों के लिए बहुत तेज़ समाधान । टेल ऑप्शन के साथ पॉवरशेल गेट-कंटेंट cmdlet का उपयोग करें। पॉवरशेल कॉलिंग थोड़ा उपरिव्यय देगा, लेकिन बड़ी फ़ाइलों के लिए यह बेकार है

using System.Management.Automation;

const string FILE_PATH = @"d:\temp\b_media_27_34_0000_25393.txt";
var ps = PowerShell.Create();
ps.AddCommand("Get-Content")
    .AddParameter("Path", FILE_PATH)
    .AddParameter("Tail", 1);
var psResults = ps.Invoke();
var lastLine = psResults.FirstOrDefault()?.BaseObject.ToString();

ps.Dispose();

आवश्यक शक्तियां संदर्भ

C: \ Program Files (x86) \ Reference Assemblies \ Microsoft \ WindowsPowerShell \ 3.0 \ System.Management.Automation.dll


1

मैं भी अपना समाधान जोड़ता हूं। कुछ उत्तरों को पढ़ने के बाद, वास्तव में मेरे मामले में कुछ भी फिट नहीं हुआ। जब तक मैं एक LineFeed नहीं पाती, तब तक मैं पीछे से बाइट पढ़ रहा हूं, फिर मैं बफर के बिना एकत्र किए गए बाइट्स को स्ट्रिंग के रूप में वापस ले रहा हूं ।

उपयोग:

var reader = new ReverseTextReader(path);
while (!reader.EndOfStream)
{
    Console.WriteLine(reader.ReadLine());  
}

कार्यान्वयन:

public class ReverseTextReader
{
    private const int LineFeedLf = 10;
    private const int LineFeedCr = 13;
    private readonly Stream _stream;
    private readonly Encoding _encoding;

    public bool EndOfStream => _stream.Position == 0;

    public ReverseTextReader(Stream stream, Encoding encoding)
    {
        _stream = stream;
        _encoding = encoding;
        _stream.Position = _stream.Length;
    }

    public string ReadLine()
    {
        if (_stream.Position == 0) return null;

        var line = new List<byte>();
        var endOfLine = false;
        while (!endOfLine)
        {
            var b = _stream.ReadByteFromBehind();

            if (b == -1 || b == LineFeedLf)
            {
                endOfLine = true;
            } 
            line.Add(Convert.ToByte(b));
        }

        line.Reverse();
        return _encoding.GetString(line.ToArray());
    }
}

public static class StreamExtensions
{
    public static int ReadByteFromBehind(this Stream stream)
    {
        if (stream.Position == 0) return -1;

        stream.Position = stream.Position - 1;
        var value = stream.ReadByte();
        stream.Position = stream.Position - 1;
        return value;
    }
}

0

मैं इसी तरह का काम करना चाहता था। यहाँ मेरा कोड है। यह वर्ग अस्थायी फ़ाइलों को बनाएगा जिसमें बड़ी फ़ाइल का हिस्सा होगा। यह मेमोरी ब्लोटिंग से बचाएगा। उपयोगकर्ता निर्दिष्ट कर सकता है कि क्या वह फ़ाइल उलटाना चाहता है। तदनुसार यह सामग्री को उल्टे तरीके से लौटाएगा।

इस वर्ग का उपयोग किसी भी फ़ाइल में बड़ी संख्या में डेटा को ब्लोटिंग मेमोरी के बिना लिखने के लिए भी किया जा सकता है।

कृपया प्रतिक्रिया दें।

        using System;
        using System.Collections.Generic;
        using System.Diagnostics;
        using System.IO;
        using System.Linq;
        using System.Text;
        using System.Threading.Tasks;

        namespace BigFileService
        {    
            public class BigFileDumper
            {
                /// <summary>
                /// Buffer that will store the lines until it is full.
                /// Then it will dump it to temp files.
                /// </summary>
                public int CHUNK_SIZE = 1000;
                public bool ReverseIt { get; set; }
                public long TotalLineCount { get { return totalLineCount; } }
                private long totalLineCount;
                private int BufferCount = 0;
                private StreamWriter Writer;
                /// <summary>
                /// List of files that would store the chunks.
                /// </summary>
                private List<string> LstTempFiles;
                private string ParentDirectory;
                private char[] trimchars = { '/', '\\'};


                public BigFileDumper(string FolderPathToWrite)
                {
                    this.LstTempFiles = new List<string>();
                    this.ParentDirectory = FolderPathToWrite.TrimEnd(trimchars) + "\\" + "BIG_FILE_DUMP";
                    this.totalLineCount = 0;
                    this.BufferCount = 0;
                    this.Initialize();
                }

                private void Initialize()
                {
                    // Delete existing directory.
                    if (Directory.Exists(this.ParentDirectory))
                    {
                        Directory.Delete(this.ParentDirectory, true);
                    }

                    // Create a new directory.
                    Directory.CreateDirectory(this.ParentDirectory);
                }

                public void WriteLine(string line)
                {
                    if (this.BufferCount == 0)
                    {
                        string newFile = "DumpFile_" + LstTempFiles.Count();
                        LstTempFiles.Add(newFile);
                        Writer = new StreamWriter(this.ParentDirectory + "\\" + newFile);
                    }
                    // Keep on adding in the buffer as long as size is okay.
                    if (this.BufferCount < this.CHUNK_SIZE)
                    {
                        this.totalLineCount++; // main count
                        this.BufferCount++; // Chunk count.
                        Writer.WriteLine(line);
                    }
                    else
                    {
                        // Buffer is full, time to create a new file.
                        // Close the existing file first.
                        Writer.Close();
                        // Make buffer count 0 again.
                        this.BufferCount = 0;
                        this.WriteLine(line);
                    }
                }

                public void Close()
                {
                    if (Writer != null)
                        Writer.Close();
                }

                public string GetFullFile()
                {
                    if (LstTempFiles.Count <= 0)
                    {
                        Debug.Assert(false, "There are no files created.");
                        return "";
                    }
                    string returnFilename = this.ParentDirectory + "\\" + "FullFile";
                    if (File.Exists(returnFilename) == false)
                    {
                        // Create a consolidated file from the existing small dump files.
                        // Now this is interesting. We will open the small dump files one by one.
                        // Depending on whether the user require inverted file, we will read them in descending order & reverted, 
                        // or ascending order in normal way.

                        if (this.ReverseIt)
                            this.LstTempFiles.Reverse();

                        foreach (var fileName in LstTempFiles)
                        {
                            string fullFileName = this.ParentDirectory + "\\" + fileName;
// FileLines will use small memory depending on size of CHUNK. User has control.
                            var fileLines = File.ReadAllLines(fullFileName);

                            // Time to write in the writer.
                            if (this.ReverseIt)
                                fileLines = fileLines.Reverse().ToArray();

                            // Write the lines 
                            File.AppendAllLines(returnFilename, fileLines);
                        }
                    }

                    return returnFilename;
                }
            }
        }

इस सेवा का उपयोग इस प्रकार किया जा सकता है -

void TestBigFileDump_File(string BIG_FILE, string FOLDER_PATH_FOR_CHUNK_FILES)
        {
            // Start processing the input Big file.
            StreamReader reader = new StreamReader(BIG_FILE);
            // Create a dump file class object to handle efficient memory management.
            var bigFileDumper = new BigFileDumper(FOLDER_PATH_FOR_CHUNK_FILES);
            // Set to reverse the output file.
            bigFileDumper.ReverseIt = true;
            bigFileDumper.CHUNK_SIZE = 100; // How much at a time to keep in RAM before dumping to local file.

            while (reader.EndOfStream == false)
            {
                string line = reader.ReadLine();
                bigFileDumper.WriteLine(line);
            }
            bigFileDumper.Close();
            reader.Close();

            // Get back full reversed file.
            var reversedFilename = bigFileDumper.GetFullFile();
            Console.WriteLine("Check output file - " + reversedFilename);
        }

0

यहां पहले से ही अच्छे उत्तर हैं, और यहां एक और LINQ- संगत वर्ग का उपयोग कर सकते हैं जो बड़ी फ़ाइलों के लिए प्रदर्शन और समर्थन पर केंद्रित है। यह एक "\ r \ n" लाइन टर्मिनेटर मानता है।

उपयोग :

var reader = new ReverseTextReader(@"C:\Temp\ReverseTest.txt");
while (!reader.EndOfStream)
    Console.WriteLine(reader.ReadLine());

ReverseTextReader वर्ग :

/// <summary>
/// Reads a text file backwards, line-by-line.
/// </summary>
/// <remarks>This class uses file seeking to read a text file of any size in reverse order.  This
/// is useful for needs such as reading a log file newest-entries first.</remarks>
public sealed class ReverseTextReader : IEnumerable<string>
{
    private const int BufferSize = 16384;   // The number of bytes read from the uderlying stream.
    private readonly Stream _stream;        // Stores the stream feeding data into this reader
    private readonly Encoding _encoding;    // Stores the encoding used to process the file
    private byte[] _leftoverBuffer;         // Stores the leftover partial line after processing a buffer
    private readonly Queue<string> _lines;  // Stores the lines parsed from the buffer

    #region Constructors

    /// <summary>
    /// Creates a reader for the specified file.
    /// </summary>
    /// <param name="filePath"></param>
    public ReverseTextReader(string filePath)
        : this(new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read), Encoding.Default)
    { }

    /// <summary>
    /// Creates a reader using the specified stream.
    /// </summary>
    /// <param name="stream"></param>
    public ReverseTextReader(Stream stream)
        : this(stream, Encoding.Default)
    { }

    /// <summary>
    /// Creates a reader using the specified path and encoding.
    /// </summary>
    /// <param name="filePath"></param>
    /// <param name="encoding"></param>
    public ReverseTextReader(string filePath, Encoding encoding)
        : this(new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read), encoding)
    { }

    /// <summary>
    /// Creates a reader using the specified stream and encoding.
    /// </summary>
    /// <param name="stream"></param>
    /// <param name="encoding"></param>
    public ReverseTextReader(Stream stream, Encoding encoding)
    {          
        _stream = stream;
        _encoding = encoding;
        _lines = new Queue<string>(128);            
        // The stream needs to support seeking for this to work
        if(!_stream.CanSeek)
            throw new InvalidOperationException("The specified stream needs to support seeking to be read backwards.");
        if (!_stream.CanRead)
            throw new InvalidOperationException("The specified stream needs to support reading to be read backwards.");
        // Set the current position to the end of the file
        _stream.Position = _stream.Length;
        _leftoverBuffer = new byte[0];
    }

    #endregion

    #region Overrides

    /// <summary>
    /// Reads the next previous line from the underlying stream.
    /// </summary>
    /// <returns></returns>
    public string ReadLine()
    {
        // Are there lines left to read? If so, return the next one
        if (_lines.Count != 0) return _lines.Dequeue();
        // Are we at the beginning of the stream? If so, we're done
        if (_stream.Position == 0) return null;

        #region Read and Process the Next Chunk

        // Remember the current position
        var currentPosition = _stream.Position;
        var newPosition = currentPosition - BufferSize;
        // Are we before the beginning of the stream?
        if (newPosition < 0) newPosition = 0;
        // Calculate the buffer size to read
        var count = (int)(currentPosition - newPosition);
        // Set the new position
        _stream.Position = newPosition;
        // Make a new buffer but append the previous leftovers
        var buffer = new byte[count + _leftoverBuffer.Length];
        // Read the next buffer
        _stream.Read(buffer, 0, count);
        // Move the position of the stream back
        _stream.Position = newPosition;
        // And copy in the leftovers from the last buffer
        if (_leftoverBuffer.Length != 0)
            Array.Copy(_leftoverBuffer, 0, buffer, count, _leftoverBuffer.Length);
        // Look for CrLf delimiters
        var end = buffer.Length - 1;
        var start = buffer.Length - 2;
        // Search backwards for a line feed
        while (start >= 0)
        {
            // Is it a line feed?
            if (buffer[start] == 10)
            {
                // Yes.  Extract a line and queue it (but exclude the \r\n)
                _lines.Enqueue(_encoding.GetString(buffer, start + 1, end - start - 2));
                // And reset the end
                end = start;
            }
            // Move to the previous character
            start--;
        }
        // What's left over is a portion of a line. Save it for later.
        _leftoverBuffer = new byte[end + 1];
        Array.Copy(buffer, 0, _leftoverBuffer, 0, end + 1);
        // Are we at the beginning of the stream?
        if (_stream.Position == 0)
            // Yes.  Add the last line.
            _lines.Enqueue(_encoding.GetString(_leftoverBuffer, 0, end - 1));

        #endregion

        // If we have something in the queue, return it
        return _lines.Count == 0 ? null : _lines.Dequeue();
    }

    #endregion

    #region IEnumerator<string> Interface

    public IEnumerator<string> GetEnumerator()
    {
        string line;
        // So long as the next line isn't null...
        while ((line = ReadLine()) != null)
            // Read and return it.
            yield return line;
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        throw new NotImplementedException();
    }

    #endregion
}

0

यदि कोई अन्य व्यक्ति इस पार आता है, तो मैंने इसे निम्नलिखित पॉवरशेल स्क्रिप्ट के साथ हल किया, जिसे आसानी से थोड़ी सी मेहनत के साथ C # स्क्रिप्ट में बदला जा सकता है।

[System.IO.FileStream]$fileStream = [System.IO.File]::Open("C:\Name_of_very_large_file.log", [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::ReadWrite)
[System.IO.BufferedStream]$bs = New-Object System.IO.BufferedStream $fileStream;
[System.IO.StreamReader]$sr = New-Object System.IO.StreamReader $bs;


$buff = New-Object char[] 20;
$seek = $bs.Seek($fileStream.Length - 10000, [System.IO.SeekOrigin]::Begin);

while(($line = $sr.ReadLine()) -ne $null)
{
     $line;
}

यह मूल रूप से एक फ़ाइल के अंतिम 10,000 वर्णों से पढ़ना शुरू करता है, प्रत्येक पंक्ति को आउटपुट करता है।


यह पिछले 10,000 बाइट्स से आगे पढ़ा जाएगा, अंत से शुरू होने तक पीछे नहीं। इसके अलावा, सिर्फ क्यों नहीं .Seek(-10000, [System.IO.SeekOrigin]::End);?
— AKX
हमारी साइट का प्रयोग करके, आप स्वीकार करते हैं कि आपने हमारी Cookie Policy और निजता नीति को पढ़ और समझा लिया है।
Licensed under cc by-sa 3.0 with attribution required.