c檔案操作的一般流程

來源:互聯網
上載者:User

發表於: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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.