1try: 2 import uerrno 3 import uos 4except ImportError: 5 print("SKIP") 6 raise SystemExit 7 8try: 9 uos.VfsFat 10except AttributeError: 11 print("SKIP") 12 raise SystemExit 13 14 15class RAMFS: 16 17 SEC_SIZE = 512 18 19 def __init__(self, blocks): 20 self.data = bytearray(blocks * self.SEC_SIZE) 21 22 def readblocks(self, n, buf): 23 # print("readblocks(%s, %x(%d))" % (n, id(buf), len(buf))) 24 for i in range(len(buf)): 25 buf[i] = self.data[n * self.SEC_SIZE + i] 26 27 def writeblocks(self, n, buf): 28 # print("writeblocks(%s, %x)" % (n, id(buf))) 29 for i in range(len(buf)): 30 self.data[n * self.SEC_SIZE + i] = buf[i] 31 32 def ioctl(self, op, arg): 33 # print("ioctl(%d, %r)" % (op, arg)) 34 if op == 4: # MP_BLOCKDEV_IOCTL_BLOCK_COUNT 35 return len(self.data) // self.SEC_SIZE 36 if op == 5: # MP_BLOCKDEV_IOCTL_BLOCK_SIZE 37 return self.SEC_SIZE 38 39 40try: 41 bdev = RAMFS(50) 42except MemoryError: 43 print("SKIP") 44 raise SystemExit 45 46uos.VfsFat.mkfs(bdev) 47vfs = uos.VfsFat(bdev) 48uos.mount(vfs, "/ramdisk") 49uos.chdir("/ramdisk") 50 51# file IO 52f = open("foo_file.txt", "w") 53print(str(f)[:17], str(f)[-1:]) 54f.write("hello!") 55f.flush() 56f.close() 57f.close() # allowed 58try: 59 f.write("world!") 60except OSError as e: 61 print(e.args[0] == uerrno.EINVAL) 62 63try: 64 f.read() 65except OSError as e: 66 print(e.args[0] == uerrno.EINVAL) 67 68try: 69 f.flush() 70except OSError as e: 71 print(e.args[0] == uerrno.EINVAL) 72 73try: 74 open("foo_file.txt", "x") 75except OSError as e: 76 print(e.args[0] == uerrno.EEXIST) 77 78with open("foo_file.txt", "a") as f: 79 f.write("world!") 80 81with open("foo_file.txt") as f2: 82 print(f2.read()) 83 print(f2.tell()) 84 85 f2.seek(0, 0) # SEEK_SET 86 print(f2.read(1)) 87 88 f2.seek(0, 1) # SEEK_CUR 89 print(f2.read(1)) 90 f2.seek(2, 1) # SEEK_CUR 91 print(f2.read(1)) 92 93 f2.seek(-2, 2) # SEEK_END 94 print(f2.read(1)) 95 96# using constructor of FileIO type to open a file 97# no longer working with new VFS sub-system 98# FileIO = type(f) 99# with FileIO("/ramdisk/foo_file.txt") as f: 100# print(f.read()) 101 102# dirs 103vfs.mkdir("foo_dir") 104 105try: 106 vfs.rmdir("foo_file.txt") 107except OSError as e: 108 print(e.args[0] == 20) # uerrno.ENOTDIR 109 110vfs.remove("foo_file.txt") 111print(list(vfs.ilistdir())) 112