向U盘写文件的C代码
[@more@]948 int atm_monitor_write_file(const char* buffer, const ssize_t len)949 {
950 int i = 0;
951 int fileId = -1;
952 int ret = -1;
953 int writeLen = -1;
954 struct stat fileStat;
955 char mountedPath[64]; /**< 设备挂载路径 /usb-sdX */
956 char testPath[9][64] =
957 {
958 "/tmp/usb-sda1",
959 "/tmp/usb-sdb1",
960 "/tmp/usb-sdc1",
961 "/tmp/usb-sdd1",
962 "/tmp/usb-sde1",
963 "/tmp/usb-sdf1",
964 "/tmp/usb-sdg1",
965 "/tmp/usb-sdh1",
966 "/tmp/usb-sdi1",
967 };
968 char filePath[128]; /**< 待写入文件路径 */
969
970 for(i = 0; i < 9; i++)
971 {
972 ret = stat(testPath[i], &fileStat);
973 if(!ret)
974 {
975 memcpy(mountedPath, testPath[i], sizeof(mountedPath));
976 break;
977 }
978 }
979
980 if(ret)
981 {
982 /**< TODO: notify GUI */
983 GD_DP(("no usb device!n"));
984 ret = APP_FAIL;
985 goto EXIT0;
986 }
987
988 sprintf(filePath, "%s/card.log", mountedPath);
989
990 if((fileId = open(filePath, O_WRONLY | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) == -1)
991 {
992 /**< TODO: notify GUI */
993 GD_DP(("Cannot open file %s!n",filePath));
994 ret = APP_FAIL;
995 goto EXIT0;
996 }
997
998 writeLen = write(fileId, buffer, len);
999 if(writeLen != -1)
1000 {
1001 ret = APP_SUCCESS;
1002 }
1003 else
1004 {
1005 GD_DP(("write data failedn"));
1006 ret = APP_FAIL;
1007 }
1008
1009 EXIT0:
1010 if(-1 != fileId)
1011 {
1012 fsync(fileId);//只对文件描述符制定单一文件起作用,并等待磁盘操作结束,然后返回
1013 close(fileId);
1014 fileId = -1;
1015 }
1016
1017 return ret;
1018 }
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/23168012/viewspace-1046759/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/23168012/viewspace-1046759/