c语言fopen追加模式下fseek失效

来源:互联网 发布:数据服务健康状况警报 编辑:程序博客网 时间:2024/05/24 01:02

转载:http://www.cnblogs.com/rusty/archive/2011/11/17/2253069.html

 
 
c语言fopen追加模式下fseek失效

 

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

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+即可。

0 0
原创粉丝点击