Skip to content

Instantly share code, notes, and snippets.

@Zirak

Zirak/LineIO.cs Secret

Created March 29, 2013 01:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Zirak/b4a1f0ad9cfd53f8a152 to your computer and use it in GitHub Desktop.
Save Zirak/b4a1f0ad9cfd53f8a152 to your computer and use it in GitHub Desktop.
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace LineIO {
public class LineReader : StreamReader {
public char separator = '\t';
private bool skip = false;
public LineReader (string path, bool skipFirst = true)
: base(path, Encoding.UTF8) {
this.skip = skipFirst;
}
/// <summary>
/// Consumes the next line in the file
/// </summary>
/// <returns>Data present in line</returns>
//the new keyword here is c#'s solution to its previously ridiculous
// overriding restrictions
public new List<string> ReadLine () {
if (this.skip) {
this.skip = false;
base.ReadLine();
}
string line = base.ReadLine();
if (line == null) {
return null;
}
List<string> ret = new List<string>();
StringBuilder hanz = new StringBuilder();
foreach (char ch in line) {
if (ch == this.separator) {
ret.Add(hanz.ToString());
hanz.Clear();
}
else {
hanz.Append(ch);
}
}
if (hanz.Length > 0) {
ret.Add(hanz.ToString());
}
hanz.Clear();
return ret;
}
}
public class LineWriter : StreamWriter {
public char separator = '\t';
public LineWriter (string path)
: base(path, false, Encoding.UTF8) { }
/// <summary>
/// Dumps the content of data into the file
/// </summary>
/// <param name="data">Stuff to write</param>
//wow, I'm doing a really bad job at documenting this.
//on the other hand, the code here is so clean!
public void WriteLine (List<string> data) {
base.WriteLine(this.Format(data));
}
private string Format (List<string> data) {
return string.Join(this.separator.ToString(), data);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment