警惕fopen,a,a+方式在 文件 定位上的问题!!!!

void my_trace(int type ,char *title,unsigned char *Data,int DataLen) { int ihex,ichar,isp; FILE *fp; long * counter; long tmp; int rv; char t[100]; fp=OpenLog(type,&counter,0); if (!fp) return; tmp=GetAllLogFileSize(); log("file size=%ld,Max=%ld/n",tmp,(long)MAX_LOG_SIZE); //check the file size if((long)MAX_LOG_SIZE<GetAllLogFileSize()) { rewind(fp); // rv=fseek(fp,0,SEEK_SET);//seek to the file start //rv=-1; if(rv) perror("fseek"); tmp=ftell(fp); log("fseek=%ld/n",tmp); ResetCounter(type); log("ResetCounter,and seek to the begin./n"); } sprintf(t,"asdfasdfasdfasdfasdf"); fwrite(t,strlen(t),1,fp); return; }

不管我如何修改代码,保证写入的可读性,可惜每次写入的内容都被写到文件尾部了。。。狂汗。

为此我 google了下

 

http://bbs.chinaunix.net/viewthread.php?tid=866761

这里说的比较明确

因为fopen(3)的"a"参数非常可能导致库代码用"O_APPEND"参数调用open(2)
解决之道:
用r+打开,手工fseek
FILE * OpenFileStream(char * file) { FILE * stream; char cmd[256]; stream=fopen(file,"r+"); //not used a+!!! if(!stream) //file not existed. { sprintf(cmd,"touch %s",file);//create it system(cmd); stream=fopen(file,"r+"); //reopen } return stream; }

你可能感兴趣的:(Stream,cmd,File,Google,FP)