Rusty's code
@Dying in the rain.

用到编程改变文件某个字段的值,结果发现此现象。上代码:

int writepcap(char *filename,int begin,int len,char *content)
{
if(!pcap || !content)
return -1;
FILE *fp = NULL;
fp = fopen(filename,"ab");//rb+
if(!fp)
return -2;
if(-1 == fseek(fp,begin,SEEK_SET))
{
fclose(fp);
return -3;
}
//printf("curr:%ld\n",ftell(fp));
if(fwrite(content, sizeof(unsigned char), len, fp) <= 0)
{
fclose(fp);
return -4;
}
fclose(fp);
return 0;
}

 

结果发现ftell输出的位置是正确的,但是写的时候还是写在了最后面。

在linux下,man fopen看到:

a+     Open for reading and appending (writing at end of file).  The file is created if it does not exist.  The initial file 
       position for  reading is at the beginning of the file, but output is always appended to the end of the file.



原来如此。

解决办法:改为rb+即可。

posted on 2011-11-17 19:27  Rusty's code  阅读(4599)  评论(0编辑  收藏  举报