clinuxsd-cardmmc

How to create and write to a file on sdcard with linux?


I want to create a file on /dev/mmcblk0, if it doesn't exist already, and then write to it. My question is how to check if there is already such file on the sdcard and then access it, does it show up like /dev/mmcblk0/somefile?


Solution

  • You should use the command mount(8) to mount the device first. That will cause the device's filesystem to be attached to your system's file-system, and therefore, makes you able to access files on it just like you normally do. For example:

    mount /dev/mmcblk0 /home/yooo123/sdcard
    

    If all goes well, you can read and write files to it using fopen, fwrite, etc.

    FILE *fp = fopen("/home/yooo123/sdcard/file.txt", "w");
    ...
    fprintf(fp, "Hello, SD Card!\n");
    

    However, if you want to do all of that from a C program, look up the mount(2) system call.

    int mount(const char *source, const char *target,
          const char *filesystemtype, unsigned long mountflags,
          const void *data);