Search code examples
c#filefilestreamfile-handling

Keeping 2 filepointers for a file in C# as index to file content


We create Fstream1 which opens the file and stores the start of file. Now we copy the fstream1 to fstream2.

Note: fstream1 will read file upwards whereas fstream2 will read file downwards.

Before reading a chunk of data upwards or downwards the respective fstream* has to remember the initial start position.

Problem is when we read the position of both the fstream’s is moving leading to loss of the position intended to store.

Example: Consider initial fstream1.pos = 500 & fstream2.pos =500. Now if I read upwards 200 characters the fstream1.pos=300 but fstream2.pos should remain 500, in our case the fstream2.pos also becomes 300. Similarly if I read downwards.

fileStream1 = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 1, true);
fileStream2 = filestream1; // want this but without opening the file again

considering filestream would be like filepointers in C++. Note: above task is in C#.


Solution

  • Assuming that you would scan upwards or downwards on a file to locate a position int he file faster, I would suggest: -

    1) Open the file once.

    2) Keep two variables - UpPointer & DownPointer and initial them as UpPointer = DownPointer = 500 (from your example).

    3) When a read or scan is made, update the respective pointer.