Skip to content

Instantly share code, notes, and snippets.

@Varriount
Created December 18, 2013 01:30
Show Gist options
  • Save Varriount/8015894 to your computer and use it in GitHub Desktop.
Save Varriount/8015894 to your computer and use it in GitHub Desktop.
RemoveFile snippet
proc removeFile*(file: string) {.rtl, extern: "nos$1", tags: [FWriteDir].} =
## Removes the `file`. If this fails, `EOS` is raised. This does not fail
## if the file never existed in the first place.
## On Windows, ignores the read-only attribute.
when defined(Windows): # Would this be better using a template to
when useWinUnicode:
let f = newWideCString(file)
if DeleteFileW(f) == 0:
if GetLastError() == ERROR_ACCESS_DENIED:
if SetFileAttributesW(f, FILE_ATTRIBUTE_NORMAL) == 0:
OSError(OSLastError())
elif DeleteFileW(f) == 0:
OSError(OSLastError())
else:
if DeleteFile(f) == 0:
if GetLastError() == ERROR_ACCESS_DENIED:
if SetFileAttributes(f, FILE_ATTRIBUTE_NORMAL) == 0:
OSError(OSLastError())
elif DeleteFile(f) == 0:
OSError(OSLastError())
else:
if cremove(file) != 0'i32 and errno != ENOENT:
raise newException(EOS, $strerror(errno))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment