Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.IO;
- using System.Collections;
- using Microsoft.SPOT;
- namespace Netduino_ReadFile
- {
- // Only works with ASCII streams
- public class FastLineReader
- {
- protected Stream mInputStream;
- protected byte[] mFileBuffer;
- protected int mFileBufferPos;
- protected int mFileBufferLen;
- protected int mBufferSize;
- public bool EndOfStream { get; protected set; }
- /// <summary>
- ///
- /// </summary>
- /// <param name="s"></param>
- /// <param name="bufferSize">this should be your expected max line length. it is ok if too small</param>
- public FastLineReader(Stream s, int bufferSize = 256)
- {
- mInputStream = s;
- mBufferSize = bufferSize;
- mFileBuffer = new byte[bufferSize];
- mFileBufferPos = 0;
- mFileBufferLen = 0;
- EndOfStream = false;
- }
- public String ReadLine()
- {
- var lineBuffer = new char[mBufferSize];
- int lineBufferPos = 0;
- bool foundLF = false;
- while(!foundLF)
- {
- if (mFileBufferPos >= mFileBufferLen)
- {
- mFileBufferPos = 0;
- mFileBufferLen = mInputStream.Read(mFileBuffer, mFileBufferPos, mFileBuffer.Length);
- if (mFileBufferLen == 0)
- {
- EndOfStream = true;
- break; // empty file or we're finished
- }
- }
- int lfLocation = mFileBufferLen - 1;
- for (int x = mFileBufferPos; x < mFileBufferLen; ++x)
- {
- if (mFileBuffer[x] == '\n')
- {
- lfLocation = x;
- foundLF = true;
- break;
- }
- }
- var dataSize = (lfLocation + 1 - mFileBufferPos); // lfLocation is 0 based, need to increment by 1 for size
- if ((lineBufferPos + dataSize) > lineBuffer.Length)
- {
- var tempBuffer = new char[lineBufferPos + dataSize];
- Array.Copy(lineBuffer, tempBuffer, lineBuffer.Length);
- lineBuffer = tempBuffer;
- }
- for (int x = mFileBufferPos; x <= lfLocation; ++x)
- {
- lineBuffer[lineBufferPos++] = (char)mFileBuffer[x];
- }
- mFileBufferPos = lfLocation + 1;
- }
- return new String(lineBuffer, 0, lineBufferPos);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement