看板 C_and_CPP 關於我們 聯絡資訊
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) Linux C 問題(Question): Struct 賦予值 餵入的資料(Input): 1,22.996006,120.224251,9.660000,0.851000,2012/07/26-15:38:08.500 15,22.995972,120.224258,19.790001,0.148000,2012/07/26-15:38:08.500 1,22.996006,120.224251,9.660000,1.017500,2012/07/26-15:38:08.603 11,22.995972,120.224258,19.790001,0.240500,2012/07/26-15:38:08.602 15,22.995972,120.224258,19.790001,0.240500,2012/07/26-15:38:08.602 1,22.996006,120.224251,9.660000,0.962000,2012/07/26-15:38:08.703 11,22.995972,120.224258,19.790001,0.388500,2012/07/26-15:38:08.702 15,22.995972,120.224258,19.790001,0.388500,2012/07/26-15:38:08.702 . . . 筆記本裡面記載GPS的資訊(id,緯度,經度,角度,速度,時間) 預期的正確結果(Expected Output): 錯誤結果(Wrong Output): 程式碼(Code):(請善用置底文網頁, 記得排版) struct Tran_GPS { char time[24]; float latitude; float longitude; float speed; float heading; int id; //char time[24]; }; int main(int argc, char* argv[]){ char filename[30]; strcpy(filename,argv[1]); fp=fopen(filename,"r+"); char buffer[100]; char *psid,*latitude,*longitude,*heading,*speed,*Time; char *div=","; while(!feof(fp)) { fgets(buffer,100,fp); psid=strtok(buffer,div); latitude=strtok(NULL,div); longitude=strtok(NULL,div); heading=strtok(NULL,div); speed=strtok(NULL,div); Time=strtok(NULL,div); Phone_UDP.id=atoi(psid); Phone_UDP.latitude=atof(latitude); Phone_UDP.longitude=atof(longitude); Phone_UDP.speed=atof(speed); Phone_UDP.heading=atof(heading); strcpy(Phone_UDP.time, Time); printf("id:%d, latitude is %f, longitude is %f,heading is %f,speed is %f,time:%s",Phone_UDP.id,Phone_UDP.latitude,Phone_UDP.longitude,Phone_UDP.heading,Phone_UDP.speed,Phone_UDP.time); usleep(50000); } //close fclose(fp); return 0; } 補充說明(Supplement): 但每次printf Struct的第二個參數(Phone_UDP.latitude)幾乎都是錯的 都讀不到,後來改變程式碼 只修改成 struct Tran_GPS { // char time[24]; float latitude; float longitude; float speed; float heading; int id; char time[24]; }; 只把char[24]放到後面 問題就解決哩 但我完全不懂為啥我之前的程式是錯的 希望有大大幫助我解惑 因為我真的覺得之前也是對的 感謝 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.116.164.79
EdisonX:char time[24] 會收到 new line char. '\n' or "\r\n" 07/31 16:30
EdisonX:所以 buffer overflow, 加大成 char time[26] 即可。 07/31 16:30
※ 編輯: willy01 來自: 140.116.164.79 (07/31 16:35)
willy01:抱歉 剛剛有地方打錯 07/31 16:36
willy01:已修正 07/31 16:37
EdisonX:不論 char time[24] 放哪裡,buf overflow 是事實,就算改過 07/31 16:49
EdisonX:執行時沒錯,但不保證日後不會有問題。可調用strlen看多長. 07/31 16:50
willy01:感謝E大 回答 謝謝 07/31 21:57