www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Truncate is missing from std.stdio.File, will this do the trick?

reply spikespaz <spikespaz outlook.com> writes:
I needed a truncate function on the `std.stdio.File` object, so I 
made this function. Does it look okay? Are there any 
cross-platform improvements you can think of that should be added?


import std.stdio: File;

void truncate(File file, long offset) {
     version (Windows) {
         import core.sys.windows.windows: SetEndOfFile;

         file.seek(offset);
         SetEndOfFile(file.windowsHandle());
     }

     version (Posix) {
         import core.sys.posix.unistd: ftruncate;

         ftruncate(file.fileno(), offset);
     }
}
Jul 23 2018
parent Patrick Schluter <Patrick.Schluter bbox.fr> writes:
On Tuesday, 24 July 2018 at 00:15:37 UTC, spikespaz wrote:
 I needed a truncate function on the `std.stdio.File` object, so 
 I made this function. Does it look okay? Are there any 
 cross-platform improvements you can think of that should be 
 added?


 import std.stdio: File;

 void truncate(File file, long offset) {
     version (Windows) {
         import core.sys.windows.windows: SetEndOfFile;

         file.seek(offset);
         SetEndOfFile(file.windowsHandle());
     }

     version (Posix) {
         import core.sys.posix.unistd: ftruncate;

         ftruncate(file.fileno(), offset);
     }
 }
Error handling is completely missing. It should throw a FileException or something when encountering an error, and there can be a lot of errors. Here the list of errno errors that ftruncate() can fail with: EFBIG, EINTR, EINVAL, EIO, EISDIR, EPERM, EROFS, ETXTBSY and EBADF. for Windows it will be probably quite similar.
Jul 24 2018