fread 返回值
小弟写了个解析。cap文件的功能,解析到中间的时候发现fread的返回值先是小于要读取的值后来就总是小于0了,先贴上代码和文件出错时的二进制码,希望大侠们利用喝茶休息的时候帮我看看,给点建议,万分感激。
FILE *stream; char szBuf[sizeof(pcap_file_header)]; memset(szBuf,0,sizeof(pcap_file_header)); size_t nRetRead = 0; int nfile = m_strFilePath.ReverseFind('\\'); nfile = m_strFilePath.GetLength()-nfile-1; CString strFile = m_strFilePath.Right(nfile); if ((stream = fopen(strFile,"r+"))!=NULL) { fseek(stream,0,SEEK_SET); fseek(stream,0,SEEK_END); long longBytes= ftell(stream); rewind(stream); pcap_file_header pcapCheck; nRetRead = fread(szBuf,1,sizeof(pcap_file_header),stream); if (nRetRead == sizeof(pcap_file_header)) { if (pcapCheck.magic != 3435973836) { MessageBox("This is not a .cap file"); return ; } } // rewind(stream); // fseek(stream,sizeof(pcap_file_header),SEEK_SET); long loffset = sizeof(pcap_file_header); if (loffset == sizeof(pcap_file_header)) { HANDLE hThread; DWORD dwThread; hThread = CreateThread(NULL,0,MyThread,NULL,0,&dwThread); if (hThread == NULL) { MessageBox("Create Thread faild !"); } while(/*!feof(stream) && */loffset < longBytes) { PcapPacket pcappacket; nRetRead = 0; memset(&pcappacket,0,sizeof(PcapPacket)); try { nRetRead = fread(szBuf,1,sizeof(pcap_pkthdr),stream); if (nRetRead !=sizeof(pcap_pkthdr)) { int nTemp = sizeof(pcap_pkthdr) - nRetRead; while(nTemp!=0) { nRetRead = fread(szBuf+nTemp,1,nTemp,stream); if (nRetRead != nTemp) { nTemp -= nRetRead; } } loffset+=sizeof(pcap_pkthdr); } else loffset += nRetRead; pcap_pkthdr* pheader = (pcap_pkthdr*)szBuf; pcappacket.header.ts.tv_sec = pheader->ts.tv_sec; pcappacket.header.ts.tv_usec = pheader->ts.tv_usec; pcappacket.header.len = pheader->len; pcappacket.header.caplen = pheader->caplen; // rewind(stream); // fseek(stream,loffset,SEEK_SET); } catch(...) { MessageBox("Read file error! "); } try { pcappacket.pkt_data = new u_char[pcappacket.header.caplen]; } catch (...) { MessageBox("New u_char error! "); } try { nRetRead = fread(pcappacket.pkt_data,1,pcappacket.header.caplen,stream); if (nRetRead != pcappacket.header.caplen) { int nTemp = pcappacket.header.caplen - nRetRead; while(nTemp!=0) { nRetRead = fread(pcappacket.pkt_data+nTemp,1,nTemp,stream); if (nRetRead != nTemp) { nTemp -= nRetRead; } } loffset+=pcappacket.header.caplen; } else loffset += nRetRead; // rewind(stream); // fseek(stream,loffset,SEEK_SET); } catch (...) { MessageBox("Read file error! "); } g_PcapPacketdeque_cs.Lock(); try { g_PcapPacketdeque.push_back(pcappacket); } catch (...) { MessageBox("g_PcapPacketdeque error! "); } g_PcapPacketdeque_cs.Unlock(); } if (IsExit == TRUE) { CloseHandle(hThread); } MessageBox("Anlyze .cap file successfull!"); } } else MessageBox("Open .cap file error"); if (stream!= NULL) { fclose(stream); }