📄 usb.c
字号:
/* * Description: * example for usb. * * What is shown in this example: * 1. How to mount usb device * 2. How to write a file to usb device * 3. How to umount usb device */#include <stdio.h>#include <fcntl.h>#include <errno.h>#include <sys/mount.h>#include <unistd.h>const char buf[] = "MATRIX USB Example\n";int main(void){ int ret, usb_type, fd; char filename[128], target[128]; /*mount USB device*/ ret = mount("/dev/sda", "/mnt/sda", "vfat", MS_SYNCHRONOUS, NULL); if (ret == -1) { if (errno == EROFS) { printf("/dev/sda is write-protected\r\n"); return; } /*if /dev/sda not found, try /dev/sda1*/ ret = mount("/dev/sda1", "/mnt/sda1", "vfat", MS_SYNCHRONOUS, NULL); if (ret == -1) { if (errno == EROFS) { printf("/dev/sda is write-protected\r\n"); } else { printf("no device found\r\n"); } return; } else { printf("found /dev/sda1\r\n"); usb_type = 1; } } else { printf("found /dev/sda\r\n"); usb_type = 0; } if (usb_type == 0) { sprintf(filename, "/mnt/sda/tmpfile"); } else { sprintf(filename, "/mnt/sda1/tmpfile"); } /*create file on USB device*/ fd = open(filename, O_CREAT|O_WRONLY|O_TRUNC); if (fd == -1) { printf("create file failed. errno: %d\r\n", errno); } else { /*write file to USB device*/ ret = write(fd, buf, sizeof(buf)); if (ret == -1) { printf("write file failed. errno: %d\r\n", errno); } else { printf("write tmpfile to USB device ok\r\n"); } } close(fd); if (usb_type == 0) { sprintf(target, "/mnt/sda"); } else { sprintf(target, "/mnt/sda1"); } /*umount USB device*/ while (1) { ret = umount(target); if (ret != 0) { if (errno == EBUSY) { sleep(1); continue; } } printf("umount %s\r\n", target); break; }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -