Filesystems – Create and Populate FAT32 Without Mounting

fatfilesystemsUtilities

Is there a way to create a FAT32 filesystem containing a set of files, without needing to mount it or have root access?

I am developing a software application for an old operating system as a hobby, and as part of the build process I would like to package up some source files into a FAT32 disk image, then launch QEMU to boot the image and run an old compiler in it. Afterwards I would like to extract the compiled file out of the FAT32 disk image.

I can create the filesystem with mkfs.vfat, however the only way I know of to get files into and out of the image is to mount it, which typically requires root access and is not conducive to being embedded in a build process.

Ideally I am after something like the zip and unzip utilities, only instead of creating/extracting .zip files, it would create and extract disk images in FAT16 or FAT32 format.

Does anything like this exist? The only things I can find online all involve mounting the disk image.

Best Answer

Of course despite all my unsuccessful searching, I finally find the answer only moments after posting a question about it.

So the mtools package can do it like this:

# Create a 2 MB file
dd if=/dev/zero of=disk.img bs=1M count=2

# Put a FAT filesystem on it (use -F for FAT32, otherwise it's automatic)
mformat -i disk.img ::

# Add a file to it
mcopy -i disk.img example.txt ::

# List files
mdir -i disk.img ::

# Extract a file
mcopy -i disk.img ::/example.txt extracted.txt

mtools works by specifying drive letters (like C:), with the special : drive (specified as ::) referring to the image given on the command line with the -i option.

Related Question