發表於:2011-07-16 18:22:11
最近在做一個小軟體,其中有一個功能是把下載下來的一個txt檔案給分割成三個小檔案,然後分別儲存為文字文件。大檔案的格式如下:
#0#1
##########2
##########3
//這裡有個換行
其中,1,2,3假設為每個小檔案要儲存的內容,“##########”為用來識別的分割符。即,每當讀到“##########”時,就先不往下讀檔案,並將之前讀到的內容儲存下來。接著再繼續往下讀檔案,直到檔案結束。
回複於:2011-07-16 19:05:37
fread( readbuf, 1, length, f_read ); 一次
首指標A=readbuf,找到下一個位置####(指標B),得到長度A
fwrite(指標A,1,長度A,f_write_main);
找到下一個位置####(指標C),同時知道了長度B和長度C.
fwrite(指標B,1,長度B,f_write_detail);
fwrite(指標C,1,長度C,f_write_code );
回複於:2011-07-16 20:29:14
#include <stdio.h> int GetPosOffset(char *p,int len) { //返回"##########"相對*p的位移 char *tmp=p; while(len>0) { if(len-- && *tmp++=='#' ) if(len-- && *tmp++=='#' ) if( len>=4 && (*(unsigned int *) tmp)==0x23232323 ) { tmp+=4; len-=4; if(len>=4 && (*(unsigned int *) tmp)==0x23232323 ) return (tmp-p-6); } } return tmp-p; //不存在特徵串"##########" } int main() { int len,lenA,lenB; FILE *fp,*fp1,*fp2,*fp3; char *pBuf; //測試test.txt儲存內容abc#######a##########cb##########bcde# fp =fopen("test.txt","rb"); //test.txt必須存在 fp1=fopen("t1.txt","wb"); fp2=fopen("t2.txt","wb"); fp3=fopen("t3.txt","wb"); fseek(fp,0,SEEK_END); len=ftell(fp); rewind(fp); pBuf=(char *)malloc(len); len=fread(pBuf,1,len,fp);//一次 lenA=GetPosOffset(pBuf,len); fwrite(pBuf,1,lenA,fp1); lenB=GetPosOffset(pBuf+lenA+10,len-lenA); fwrite(pBuf+lenA+10,1,lenB,fp2); fwrite(pBuf+lenA+lenB+20,1,len-lenA-lenB-20,fp3); fclose(fp); fclose(fp1); fclose(fp2); fclose(fp3); free(pBuf); return 0; }
主要函數流程:
fopen
fseek
ftell
rewind
malloc
fread
fwrite
fclose
free