向隨身碟寫檔案的C程式碼

sgy618發表於2011-03-03

向隨身碟寫檔案的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/,如需轉載,請註明出處,否則將追究法律責任。

相關文章