+ off_t bytes_written = file_write_at (file, buffer, size, file->pos);
+ file->pos += bytes_written;
+ return bytes_written;
+}
+
+/* Writes SIZE bytes from BUFFER into FILE,
+ starting at offset FILE_OFS in the file.
+ The file's current position is unaffected
+ Returns the number of bytes actually written,
+ which may be less than SIZE if end of file is reached.
+ (Normally we'd grow the file in that case, but file growth is
+ not yet implemented.) */
+off_t
+file_write_at (struct file *file, const void *buffer_, off_t size,
+ off_t file_ofs)
+{
+ const uint8_t *buffer = buffer_;
+ off_t bytes_written = 0;
+
+ while (size > 0)
+ {
+ /* Starting byte offset within sector to read. */
+ off_t sector_idx = inode_byte_to_sector (file->inode, file_ofs);
+ int sector_ofs = file_ofs % DISK_SECTOR_SIZE;
+
+ /* Bytes left in file, bytes left in sector, lesser of the two. */
+ off_t file_left = inode_length (file->inode) - file_ofs;
+ int sector_left = DISK_SECTOR_SIZE - sector_ofs;
+ int min_left = file_left < sector_left ? file_left : sector_left;
+
+ /* Number of bytes to actually writen into this sector. */
+ int chunk_size = size < min_left ? size : min_left;
+ if (chunk_size == 0)
+ break;
+
+ /* If the sector contains data before or after the chunk
+ we're writing, then we need to read in the sector
+ first. Otherwise we start with a sector of all zeros. */
+ if (sector_ofs > 0 || chunk_size < sector_ofs)
+ disk_read (filesys_disk, sector_idx, file->bounce);
+ else
+ memset (file->bounce, 0, DISK_SECTOR_SIZE);
+ memcpy (file->bounce + sector_ofs, buffer + bytes_written, chunk_size);
+ disk_write (filesys_disk, sector_idx, file->bounce);
+
+ /* Advance. */
+ size -= chunk_size;
+ file_ofs += chunk_size;
+ bytes_written += chunk_size;
+ }
+
+ return bytes_written;