file_4.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. def writeToFile(self, txt, pgno, offset):
  2. n = 1024
  3. # Customize file open location for your own self
  4. fopen = open("F:/labOS/funner.dat", "r+")
  5. # moves the pointer of file towards the page number specified, as each page consists of 1024 bytes to it is multiplied by 1024
  6. # the product is then added with offset to start writing to the file from the offset specified
  7. fopen.seek(pgno*1024 + offset)
  8. # if file exists then open
  9. if fopen:
  10. fopen.seek(pgno*1024+offset)
  11. # checks whether sum of offset and len(txt) is greater than 1024 means that it actually checks whether the data inputed
  12. # by the user is greater than 1024 bytes.
  13. # for example: the word "Hassan" contains 6 letters hence it contains 6 Bytes so it will false the following condition
  14. if offset + len(txt) > 1024:
  15. buffer = txt
  16. # writes to file to the buffer array from 0 index to the difference of 1024 and offset
  17. fopen.write(buffer[0:(1024 - offset)])
  18. self.mainPage[pgno] = True
  19. # loops till 1024 - size of Byte
  20. for i in range(n):
  21. # initialized tmppg no to the respective mainPage
  22. tmppgno = self.mainPage[i]
  23. # moves the pointer as of Byte size
  24. fopen.seek(tmppgno*1024)
  25. # Writes to the file by slicing such that it starts writing from difference of 1024-offset+1 and ends at the
  26. # position returned by the difference of len(txt) and 1024-offset
  27. fopen.write(buffer[1024-offset+1: len(txt) - (1024-offset)])
  28. self.pgoffset[i] = len(txt) - (1024-offset)
  29. self.mainPage[i] = True
  30. # else if the length of text entered by the user is less than 1024
  31. else:
  32. fopen.seek(pgno*1024+offset)
  33. buffer = txt
  34. fopen.write(buffer[0:len(txt)])
  35. self.pgoffset[pgno] = len(txt) +offset
  36. fopen.close()