Search code examples
linuxcommand-linefilesystemsfat32

Add files to VFAT image without mounting


I want to create a new VFAT image and add a few files to it.

# Create file of 1MB size:
dd if=/dev/zero of=my-image.fat count=1 bs=1M
# Format file as VFAT:
mkfs.vfat ./my-image.fat

Now I want to add the files ./abc, ./def and ./ghi to the image.

How do I do that without mount -o loop or fusermount? I only want to write to a new, empty, pristine VFAT image. I don't need deleting appending or any "complicated" operations.

I tried 7z -a because 7zip can read VFAT images, but it does not know how to write to it.


Solution

  • I want to do the exact same thing as part of an image build for an embedded system. It's really annoying that the entire build, which takes ~3hrs, could be completely unattended except for the final steps which required a password in order to mount a VFAT image. Fortunately, I found a set of tools which solve the problem.

    You want mcopy provided by GNU mtools.

    Mtools is a collection of utilities to access MS-DOS disks from GNU and Unix without mounting them.

    It also supports disk images such as VFAT image files.

    As an example, the following command will copy the file hello.txt from your current directory into the subdirectory subdir of the VFAT file system in ~/images/fat_file.img:

    mcopy -i ~/images/fat_file.img hello.txt ::subdir/hello.txt
    

    There are more useful inclusions in mtools, such as mdir and mtype which are great for inspecting your image file without having to mount it.

    mdir -i ~/images/fat_file.img ::
    mdir -i ~/images/fat_file.img ::subdir
    mtype -i ~/imags/fat_file.img ::subdir/hello.txt