Created
January 2, 2013 23:14
-
-
Save gogsbread/4439250 to your computer and use it in GitHub Desktop.
Naive implementation of Copying file in reverse where 1) File size is large 2) buffering is not allowed. This is a good interview question. Not sure if the code works
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace dotNetPlayGround | |
{ | |
using System; | |
using System.IO; | |
using System.Collections.Generic; | |
/// <summary> | |
/// TODO: Update summary. | |
/// </summary> | |
public class ReverseFileCopier | |
{ | |
public static void Main() | |
{ | |
//read a byte | |
//convert byte to int | |
//check if byte is space | |
// add all buffered bytes | |
// add the space | |
// continue until stream is done. | |
// what will read() do? | |
FileStream input = new FileStream("large.txt", FileMode.Open, FileAccess.Read); | |
FileStream output = new FileStream("reverse.txt", FileMode.Create, FileAccess.ReadWrite); | |
FileStream temp = new FileStream("temp.txt", FileMode.Create, FileAccess.ReadWrite); | |
int cInt = input.ReadByte(); | |
List<byte> word = new List<byte>(); | |
while(cInt != -1){ | |
if (cInt == 32) | |
{ | |
//Copy output file to temp file. | |
//write the word to output file. | |
//write the temp file to output file. | |
//clear word. | |
// clear contents of the temp file. | |
temp.SetLength(0); | |
temp.Flush(); | |
byte[] buffer = new byte[1024]; | |
long bytesToRead = output.Length; | |
int bytesRead = 0; | |
while(bytesToRead > 0){ | |
bytesRead = output.Read(buffer,0,1024); | |
temp.Write(buffer,0,1024); | |
bytesToRead -= bytesRead; | |
} | |
temp.Seek(0,SeekOrigin.Begin); | |
output.Seek(0,SeekOrigin.Begin); | |
byte[] bytes = word.ToArray(); | |
output.Write(bytes, 0, bytes.Length); | |
bytesToRead = temp.Length; | |
bytesRead = 0; | |
while (bytesToRead > 0) | |
{ | |
bytesRead = temp.Read(buffer, 0, 1024); | |
output.Write(buffer, 0, 1024); | |
bytesToRead -= bytesRead; | |
} | |
output.Seek(0, SeekOrigin.Begin); | |
word.Clear(); | |
} | |
word.Add((byte)cInt); | |
cInt = input.ReadByte(); | |
} | |
input.Close(); | |
output.Close(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment