Last active
December 20, 2020 09:48
-
-
Save iAmGroute/04077ac020ac4921c2d389e751832b42 to your computer and use it in GitHub Desktop.
Find the last occurrence of given character in file
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
import os | |
import sys | |
def rfind_file(filename, value, blocksize, maxsize=0): | |
fd = os.open(filename, os.O_RDONLY) | |
try: | |
size = os.lseek(fd, 0, os.SEEK_END) | |
if maxsize < 0: | |
size = max(size - maxsize, 0) | |
elif maxsize > 0: | |
size = min(size, maxsize) | |
offset = ((size - 1) // blocksize) * blocksize | |
while True: | |
assert os.lseek(fd, offset, os.SEEK_SET) == offset | |
data = os.read(fd, blocksize) | |
assert len(data) == min(blocksize, size - offset) | |
index = data.rfind(value) | |
if index >= 0: return offset + index | |
offset -= blocksize | |
if offset < 0: return -1 | |
finally: | |
os.close(fd) | |
if __name__ == '__main__': | |
argc = len(sys.argv) | |
filename = sys.argv[1] | |
char = sys.argv[2].encode().decode('unicode_escape').encode() | |
assert len(char) == 1, repr(char) | |
value = char[0] | |
blocksize = int(sys.argv[3]) if argc > 3 else 65536 | |
maxsize = int(sys.argv[4]) if argc > 4 else 0 | |
res = rfind_file(filename, value, blocksize, maxsize) | |
print(res) | |
if res < 0: | |
sys.exit(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment