12 Replies - 2845 Views - Last Post: 20 October 2013 - 04:09 PM Rate Topic: -----

#1 Azzamean   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 20-October 13

Writing and Reading into a text file simultaneously.

Posted 20 October 2013 - 12:45 PM

I am attempting to write a line of code into my text file in a sorted position, that is, the string I write should be in the area with the last names starting in C. I made it where I could actually write the line into the text file at the top of my code in the comments, but it doesn't do what I want. I believe my problem is in my StreamWriter or StreamReader, but I do not know exactly what I am doing wrong. I thought it was because I am trying to read and write at the same time, as I was getting a lot of errors in previous versions from having 2 streams going on.

So, my question is, what is wrong with this? Why does it not insert the line in the correct spot?

class Program
    {
        static void Main(string[] args)
        {
            //StreamWriter unFile = new StreamWriter("Students.txt", true);
            //string newRecord = "(LIST (LIST 'Constant 'Malachi 'D ) '1234567890 '[email protected] 4.000000 )";
            //unFile.WriteLine(newRecord);
            //unFile.Close();

            FileStream fStream = new FileStream("Students.txt", FileMode.Open, FileAccess.ReadWrite);
            StreamReader inFile = new StreamReader(fStream);
            string inValue;
            string[] values;
            double GPA;
            double total = 0;
            double count = 0;
            double counter = 0;
            double counterr = 0;
            double counti = 0;
            List<string> Anderson = new List<string>();
            List<string> gpa = new List<string>();
            List<string> lines = new List<string>();
            List<string> noemail = new List<string>();


            string newLastName = "'Constant";
            string newRecord = "(LIST (LIST 'Constant 'Malachi 'D ) '1234567890 '[email protected] 4.000000 )";
            string line;
            string lastName;
            bool insertionPointFound = false;

            for (int i = 0; i < lines.Count && !insertionPointFound; i++)
            {

                line = lines[i];
                if (line.StartsWith("(LIST (LIST "))
                {
                    values = line.Split(" ".ToCharArray());
                    lastName = values[2];
                    if (newLastName.CompareTo(lastName) < 0)
                    {
                        lines.Insert(i, newRecord);
                        insertionPointFound = true;
                    }

                }


            }
            if (!insertionPointFound)
            {

                lines.Add(newRecord);
            }                  
               
                while (!inFile.EndOfStream)
                {
                    inValue = inFile.ReadLine();
                    if (inValue.StartsWith("(LIST (LIST ")) //the code goes on further but isn't related to this question
                    {


Is This A Good Question/Topic? 0
  • +

Replies To: Writing and Reading into a text file simultaneously.

#2 andrewsw   User is offline

  • palpable absurdity
  • member icon

Reputation: 6905
  • View blog
  • Posts: 28,565
  • Joined: 12-December 12

Re: Writing and Reading into a text file simultaneously.

Posted 20 October 2013 - 01:14 PM

The only insertion in your code is this line:

lines.Insert(i, newRecord);

which inserts into your List, not the file.

But we cannot insert in the middle of a text-file. (At least, not without delving into the binary-level of the file, which you don't want to do..)

FileAccess.ReadWrite really should be ReadAppend IMO, as the writing would be at the end of the file.

There are a number of approaches to reading and writing to a file, but they all involve extracting the data from the file into a temporary file, or StringBuilder, or even just a String. There's an example here at SO using a StringBuilder.

This post has been edited by andrewsw: 20 October 2013 - 01:16 PM

Was This Post Helpful? 0
  • +
  • -

#3 andrewsw   User is offline

  • palpable absurdity
  • member icon

Reputation: 6905
  • View blog
  • Posts: 28,565
  • Joined: 12-December 12

Re: Writing and Reading into a text file simultaneously.

Posted 20 October 2013 - 01:24 PM

Her's an example which uses what is sometimes called, I believe, a father/son update - but it's in VB:

    Dim sr As New StreamReader(filename)
    Dim sw As New StreamWriter(Path.ChangeExtension(filename, "tmp"))
    Dim buffer As String = sr.ReadLine()
    While buffer IsNot Nothing
        sw.WriteLine(buffer.Replace("foo", "bar"))
        buffer = sr.ReadLine()
    End While
    sr.Close()
    sw.Close()
    File.Copy(Path.ChangeExtension(filename, "tmp"), filename, True)
    File.Delete(Path.ChangeExtension(filename, "tmp"))

[Actually, I don't think it's really called a father/son update, this is just something someone made up ;) ]
Was This Post Helpful? 0
  • +
  • -

#4 Azzamean   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 20-October 13

Re: Writing and Reading into a text file simultaneously.

Posted 20 October 2013 - 01:40 PM

This is what I am working with now
var sb = new StringBuilder();
            using (var sr = new StreamReader("Students.txt"))
            {
                string linez;
                do
                {
                    linez = sr.ReadLine();
                    sb.AppendLine(linez);
                } while (!linez.Contains("(LIST (LIST "));

                sb.Append("(LIST (LIST 'Constant 'Malachi 'D ) '1234567890 '[email protected] 4.000000 )");
                sb.Append(sr.ReadToEnd());
            }
            using (var sr = new StreamWriter("Students.txt"))
            {
                sr.Write(sb.ToString());
            }


But I am still trying to see how to get it in the correct spot. Since my entire list looks like what I am appending (that being with the (LIST (LIST 'LASTNAME 'FIRSTNAME 'INITIAL) 'PHONE# etc...

This post has been edited by andrewsw: 20 October 2013 - 02:00 PM
Reason for edit:: Removed unnecessary quote

Was This Post Helpful? 0
  • +
  • -

#5 baavgai   User is offline

  • Dreaming Coder
  • member icon


Reputation: 7507
  • View blog
  • Posts: 15,558
  • Joined: 16-October 07

Re: Writing and Reading into a text file simultaneously.

Posted 20 October 2013 - 02:05 PM

List<string> lines = new List<string>();
//...
bool insertionPointFound = false;
//...
// when you hit this loop, lines.Count==0.  So, you never actually loop.
for (int i = 0; i < lines.Count && !insertionPointFound; i++) {



When, exactly, do you load lines?

And this nasty business with parallel Lists...

You should have some kind of class. e.g.
class Student {
	public string LastName { get; set; }
	public string FirstName { get; set; }
	public string MiddleName { get; set; }
	public string ID { get; set; }
	public string Email { get; set; }
	public double Gpa { get; set; }
	public Student() { }
	public Student(string lineToParse) { /* your code here */ }
	public override string ToString() { /* your code here, make it your output line */ }
	public override bool Equals(object obj) { /* your code here, base it on last name */ }
	public override int GetHashCode() { return this.ToString().GetHashCode(); }
}



Your code would then follow:
class Students : List<Student> {
	public void Read(string fileName) {
		using (var fStream = new FileStream(fileName, FileMode.Open, FileAccess.Read)) {
			Read(new StreamReader(fStream));
		}
	}
	public void Read(TextReader reader) { /* your code here*/ }
	public void Write(TextWriter writer) { /* your code here*/ }
	public void Write(string fileName) { /* your code here*/ }
	public override void Add(Student item) {
		if (this.Contains(item)) { this.Remove(item); }
		base.Add(item);
	}
}

class Program {
	static void Main(string[] args) {
		var fileName = "Students.txt";
		Students students = new Students();
		students.Read(fileName);
		// students.Add(new Student() { LastName="Constant", FirstName="Malachi", MiddleName="D", Email="[email protected]", Gpa=4, ID=1234567890 });
		students.Add(new Student("(LIST (LIST 'Constant 'Malachi 'D ) '1234567890 '[email protected] 4.000000 )"));
		students.Write(fileName);
	}
}



Hope this helps.

This post has been edited by baavgai: 20 October 2013 - 02:06 PM

Was This Post Helpful? 0
  • +
  • -

#6 andrewsw   User is offline

  • palpable absurdity
  • member icon

Reputation: 6905
  • View blog
  • Posts: 28,565
  • Joined: 12-December 12

Re: Writing and Reading into a text file simultaneously.

Posted 20 October 2013 - 02:07 PM

Are you only looking for a single occurrence of "(LIST (LIST "?

Does your current code run? That is, without error? But please provide some sample content:

  • Sample lines from the original file
  • What output you currently end up with
  • What the output should be.

I assume you end up with "(LIST (LIST " occurring twice ;) (and you'll get an error if the file doesn't contain this text).
Was This Post Helpful? 0
  • +
  • -

#7 andrewsw   User is offline

  • palpable absurdity
  • member icon

Reputation: 6905
  • View blog
  • Posts: 28,565
  • Joined: 12-December 12

Re: Writing and Reading into a text file simultaneously.

Posted 20 October 2013 - 02:17 PM

BTW That's not a real email address in there I hope? If it is, let me know and I'll modify it.
Was This Post Helpful? 0
  • +
  • -

#8 Azzamean   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 20-October 13

Re: Writing and Reading into a text file simultaneously.

Posted 20 October 2013 - 03:00 PM

This is an example of the textfile :
(LIST (LIST 'Abell 'Lydia 'K ) '8698997679 '[email protected] 2.8262212760393526 )
(LIST (LIST 'Abell 'Rakole 'NONE ) '8697333968 '[email protected] 2.4776920039145605 )
(LIST (LIST 'Abell 'Sara 'W ) '9738836377 '[email protected] 3.44615429506383 )
(LIST (LIST 'Abner 'Megan 'L ) '8698333779 '[email protected] 2.527236502470231 )
(LIST (LIST 'Abney 'Jennifer 'L ) '8698689376 '[email protected] 1.8699795819192644 )
(LIST (LIST 'Abrams 'Katherine 'G ) '8698689337 '[email protected] 2.451663349588242 )

The output that I get is the same as if inserting my Malachi line doesn't occur. There are not errors for me to see. Thats why I am so confused here on what I am doing wrong to add this sorted line.

This post has been edited by andrewsw: 20 October 2013 - 03:05 PM
Reason for edit:: Removed unnecessary quote

Was This Post Helpful? 0
  • +
  • -

#9 andrewsw   User is offline

  • palpable absurdity
  • member icon

Reputation: 6905
  • View blog
  • Posts: 28,565
  • Joined: 12-December 12

Re: Writing and Reading into a text file simultaneously.

Posted 20 October 2013 - 03:16 PM

Reading between the lines (excuse the pun!) I would expect it to insert Malachi as the second line of the file. Does it do this?

Currently, however, you are only looking for the first occurrence of "LIST( LIST( ", you don't continue through the file once this is found, you just append the remainder of the file. You'll need to fix this.

Just for the moment though you could:

  • Look just for "LIST", in case it doesn't precisely match "LIST( LIST( " for some reason - perhaps an extra space.
  • Write to a different file to see if this changes anything.

These are typical debugging steps.
Was This Post Helpful? 0
  • +
  • -

#10 andrewsw   User is offline

  • palpable absurdity
  • member icon

Reputation: 6905
  • View blog
  • Posts: 28,565
  • Joined: 12-December 12

Re: Writing and Reading into a text file simultaneously.

Posted 20 October 2013 - 03:25 PM

Erm, you just append all the remaining content, and you are not looking for a sorted item, because you have more or less just copied and pasted the code from the page I linked to :whistling:. That code is relevant, and can be modified to meet your needs, but it obviously doesn't meet your specific requirements.

The question the guy in the linked-page asked was:

Quote

I have a text file in which i need to add some lines after a particular line is encountered.

This post has been edited by andrewsw: 20 October 2013 - 03:28 PM

Was This Post Helpful? 0
  • +
  • -

#11 Azzamean   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 20-October 13

Re: Writing and Reading into a text file simultaneously.

Posted 20 October 2013 - 03:37 PM

My old sorting method seemed to not work.. So.. I ghetto rigged it.
 class Program
    {
        static void Main(string[] args)
        {
            WritingText();
            ReadingText();
            //StreamWriter unFile = new StreamWriter("Students.txt", true);
            //string newRecord = "(LIST (LIST 'Constant 'Malachi 'D ) '1234567890 '[email protected] 4.000000 )";
            //unFile.WriteLine(newRecord);
            //unFile.Close();
        }
        public static void WritingText()
        {
            var sb = new StringBuilder();
            using (var sr = new StreamReader("Students.txt"))
            {
                string line;
                do
                {
                    line = sr.ReadLine();
                    sb.AppendLine(line);
                } while (!line.Contains("^"));

                sb.Append("(LIST (LIST 'Constant 'Malachi 'D ) '1234567890 '[email protected] 4.000000 )");
                sb.Append(sr.ReadToEnd());
            }

            using (var sr = new StreamWriter("Studentz.txt"))
            {
                sr.Write(sb.ToString());
            }
        }
         public static void ReadingText()
            {
            using (StreamReader inFile = new StreamReader("Studentz.txt"))
            { etc... with more code not needing for this



I just put a ^ at the end of Students file so it would at least add it and read it from my new Studentz file and give me results I want for adding new students. It will always append whatever students I want to add at the end. But I want it to be sorted. Any advice? I've made a lot of progress so far and almost done
Was This Post Helpful? 0
  • +
  • -

#12 andrewsw   User is offline

  • palpable absurdity
  • member icon

Reputation: 6905
  • View blog
  • Posts: 28,565
  • Joined: 12-December 12

Re: Writing and Reading into a text file simultaneously.

Posted 20 October 2013 - 03:53 PM

You can use String.Compare and when this returns a number greater than 0 you know that you can insert Malachi before the current line you are reading.
Was This Post Helpful? 0
  • +
  • -

#13 andrewsw   User is offline

  • palpable absurdity
  • member icon

Reputation: 6905
  • View blog
  • Posts: 28,565
  • Joined: 12-December 12

Re: Writing and Reading into a text file simultaneously.

Posted 20 October 2013 - 04:09 PM

Well, I suppose.. it could be something like this:

    string line;
    string malac = "(LIST (LIST 'Constant 'Malachi 'D ) etc..";
    do
    {
        line = sr.ReadLine();
        if (String.Compare(line, malac) < 0)
        {
            sb.AppendLine(line);
        } 
    } while (String.Compare(line, malac) < 0 and not the end-of-stream);
    sb.Append(malac);
    sb.Append(line);
    sb.Append(sr.ReadToEnd());

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1