fopen的返回值是其第三个参数,是类型个数,而不是多少个字符,
这里就需要feof函数判断是否达到文件末尾。
同时也要注意feof函数第一次判断到文件末尾,还会执行一次。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
int ReadBinaryFile(const char* _fileName, void* _buf, int _bufLen);
int WriteBinaryFile(const char* _fileName, void* _buf, int _bufLen);
int main(int argc, char *argv[])
{
if(argc < 2)
{
printf("main argc < 2\r\n");
exit(0);
}
printf("input file=%s\n", argv[1]);
int nReadnum = 512;
int nfilenum = 512;
int nReadretnum = 0;
unsigned char sendBuffer[512];
FILE * fp = NULL;
fp = fopen(argv[1], "rb"); // 必须确保是以 二进制写入的形式打开
if( NULL == fp )
{
return (-1);
}
fseek (fp , 0 , SEEK_END);
nfilenum = ftell (fp);
rewind (fp);
int read_num = 0;
while(1)
{
printf("=0=fread nReadnum=%d\n", nReadnum);
nReadretnum = fread(&sendBuffer, nReadnum, 1, fp); // nReadretnum有可能小雨512
printf("=1=fread nReadretnum=%d nfilenum=%d read_num=%d\n", nReadretnum, nfilenum, read_num);
if(nReadretnum != 0)
{
read_num ++;
printf("=11=fread nReadretnum=%d\n", nReadretnum);
WriteBinaryFile("./1.h264", sendBuffer, nReadnum);
}
else
{
printf("=121=fread nReadretnum=%d\n", nReadretnum);
if(feof(fp) != 0)
{
printf("=1211=fread nReadretnum=%d nfilenum - read_num * nReadnum=%d\n", nReadretnum, nfilenum - read_num * nReadnum);
if(nfilenum - read_num * nReadnum > 0)
{
nReadretnum = fread(&sendBuffer, nfilenum - read_num * nReadnum, 1, fp); // nReadretnum一定小雨512
printf("=12111=fread nReadretnum=%d nfilenum - read_num * nReadnum=%d\n", nReadretnum, nfilenum - read_num * nReadnum);
if(nReadretnum == 0)
{
//
read_num ++;
printf("=121111=fread nReadretnum=%d\n", nReadretnum);
WriteBinaryFile("./1.h264", sendBuffer, nfilenum - read_num * nReadnum);
break;
}
else
{
printf("=121112=fread nReadretnum=%d\n", nReadretnum);
}
}
printf("=122=fread nReadretnum=%d\n", nReadretnum);
}
break;
}
printf("=2=fread nReadretnum=%d\n", nReadretnum);
}
fclose(fp);
//
fromLen = sizeof(fromAddr);
//
if(recvfrom(sock,sendBuffer,128,0,(struct sockaddr*)&fromAddr,&fromLen)<0)
//
{
//
printf("()recvfrom() error\r\n");
//
close(sock);
//
exit(1);
//
}
//
printf("recvfrom() result:%s\r\n",sendBuffer);
return 0;
}
/*
* 函数说明: 写二进制文件
* 参数描述: _fileName, 文件名称
* _buf, 要写的内存缓冲。
* _bufLen, 内存缓冲的长度
* 返回值: 0, 成功
* -1, 失败
*
*/
int WriteBinaryFile(const char* _fileName, void* _buf, int _bufLen)
{
FILE * fp = NULL;
if( NULL == _buf || _bufLen <= 0 ) return (-1);
fp = fopen(_fileName, "ab+"); // 必须确保是以 二进制写入的形式打开
if( NULL == fp )
{
return (-1);
}
fwrite(_buf, _bufLen, 1, fp); //二进制写
fclose(fp);
fp = NULL;
return 0;
}