Delete last 4 bytes of a file without opening a file?

This is a question that was asked to me in an interview and still could not find a way to do this -

Suppose I have a .txt file and I want to remove the last 4 characters from the contents of this file without opening the file. First question: is this really possible? If so, what is the way to do this?

+4
source share
3 answers

I think you cannot read the contents of the file. Therefore, if you can "open" it with write access only:

using (var fileStream = File.Open("initDoc.txt", FileMode.Open, FileAccess.Write))
{
    fileStream.SetLength(fileStream.Length - 4);
}  

Of course, you will need additional checks to make sure that you subtract the correct number of bytes depending on the encoding, and do not subtract more than the length, etc.

FileMode.Open, FileStream, SafeFileHandle. SafeFileHandle , # Interop. , "UnmanagedFileLoader":

var unmanagedFileLoader = new UnmanagedFileLoader("initDoc.txt");

using (var fileStream = new FileStream(unmanagedFileLoader.Handle, FileAccess.Write))
{
    fileStream.SetLength(fileStream.Length - 4);
}

UnmanagedFileLoader CreateFile :

handleValue = CreateFile(Path, GENERIC_WRITE, 0, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);

, SafeFileHandle, :

http://msdn.microsoft.com/en-us/library/microsoft.win32.safehandles.safefilehandle%28v=vs.110%29.aspx

FileStream, - StreamReader StreamWriter, StreamReader 4 , StreamWriter. - FileStream.

+3

EDIT: , " " " ".

, :

  • ,
  • , : MFT ( NTFS), FAT.. ..
  • ,
  • () 4 , :)
+2

If you are worried about reading all the data for a long file: this is optional. If we assume that you really mean bytes, simply:

using (var file = File.Open(path, FileMode.Open, FileAccess.Write)) {
    file.SetLength(file.Length - 4);
}

this means not reading the contents of the file.

If you mean characters, then you need to carefully consider the encoding - 4 characters are not necessarily 4 bytes.

0
source

All Articles