How to add a string to a big file in csharp !

From: zjut (zjut_at_discussions.microsoft.com)
Date: 11/04/04


Date: Wed, 3 Nov 2004 20:05:03 -0800

I want to add a string to the file and the file is sort by letter! for
examply:
the follow file is a big file
//////////////////////
abort
black
cabbage
dog
egg
fly
.
.
////////////////////
and now i want to add "dad" into it ! Just after "cabbage" and at the front
of "dog"! Because of so many word in file so i need to adopt binary search to
find the location !

/// <summary>
/// want to find the word from given file
/// </summary>
/// <param name="?"></param>

private bool find(string word)
{
if (word == null)
{
throw new ArgumentNullException("word is null.");
}

StreamReader sr = new StreamReader(file.FullName); //file is object of
FileInfo
lock(this)
{
//Check the word is in the first!
string str = sr.ReadLine();
if (str == null)
{
return false;
}
if (string.Compare(str.Trim(),word))
return true;
}

// binary search starts
FileStream fs = File.OpenRead(file.FullName);
long lower = 0;
long upper = fs.Length - 1;
while (lower <= upper)
{
long index = (lower + upper) / 2;
fs.seek(index,SeekOrigin.End);

// read off an incomplete line
str = fs.Read();
////i donot know how to set the parameters of Read() so that it can read a
line

// the line might be null if it's the end of file
int t = str == null ? -1
: string.Compare(word, str.trim());
// found it
if (t == 0)
{
return true;
}
if (t > 0)
{
lower = index + 1;
}
else
{
upper = index - 1;
}
}
}

that is the fuction of method and my question is
1: the FileStream is fitable in it ?
2 : string.Compare is fitable in it ?
3: is there any method i can do it better ?

thanx of all !



Relevant Pages

  • How to add a string to a big file in csharp !
    ... want to add a string to the file and the file is sort by letter! ... Just after "cabbage" and at the front ... string str = sr.ReadLine; ... long upper = fs.Length - 1; ...
    (microsoft.public.dotnet.general)
  • Re: unicode codecs
    ... Ivan Voras wrote: ... > from the upper half of code page, ... Are you absolutely certain that typeis str? ... Are you absolutely certain the constant is the literal string 'x'? ...
    (comp.lang.python)
  • Re: ISAM error when trying to create tablelink
    ... Dim tDef As DAO.TableDef ... Doug Steele, Microsoft Access MVP ... Dim str As String ...
    (microsoft.public.access.modulesdaovba)
  • Re: Using the Dictionary object
    ... Private Sub LV_ItemCheck ... Dim Str As String ... MyNext = MyNext - 1 ...
    (microsoft.public.excel.programming)
  • Re: str() should convert ANY object to a string without EXCEPTIONS !
    ... For strings, ... 'ascii' codec can't encode character u'\ue863' in ... And it is correct to fail, ASCII is only defined within range, ... If that str() function has returned anything but error on this, ...
    (comp.lang.python)