现在的位置: 首页 > 综合 > 正文

文件二进制的读写

2012年11月11日 ⁄ 综合 ⁄ 共 2315字 ⁄ 字号 评论关闭

读文件并以二进制形势转到另一新建文件中

/****************************************
*edward nic
*2007.04.25
*
***************************************
*/

#include 
<stdio.h>
#include 
<stdlib.h>
#include 
<sys\stat.h>  //for fstst()
int main()
{
    
struct stat statBuffer ;
    FILE        
*fpin , *fpout;
    
char        *p ;
    
int         FileSize ;

    fpin 
= fopen("1.rar""rb") ;
    fstat(fileno(fpin), 
&statBuffer) ;
    FileSize 
= statBuffer.st_size ;
    printf(
"%d\t", statBuffer.st_size) ;
    
    p 
= (char *)malloc(FileSize * sizeof(char)) ;

    fread(p, FileSize, 
1 , fpin) ;

    fpout 
= fopen("2.rar""wb") ;
    fwrite(p, FileSize, 
1 , fpout) ;

    free(p) ;
    fclose(fpout) ;
    fclose(fpin) ;
    
return 0 ;
}

读类似“\xff\xaa\x02…”文本文件并还原到二进制文件
1。把二进制文件转\xff\xaa\x02…”文本型式

//需要 unsigned char

#include 
<stdio.h>
#include 
<stdlib.h>
#include 
<sys\stat.h>  //for fstst()
int main()
{
    
struct stat   statBuffer ;
    FILE          
*fpin , *fpout;
    unsigned 
char *p ;
    
int           FileSize ;
    
int           i ;
    
    
//read data
    fpin = fopen("1.rar""rb") ;
    fstat(fileno(fpin), 
&statBuffer) ;
    FileSize 
= statBuffer.st_size ;
    printf(
"file size is:%dbytes\n", statBuffer.st_size) ;
    
    p 
= (unsigned char *)malloc(FileSize * sizeof(char)) ;
    
    
for (i = 0; i < FileSize; ++i)
    
{
        fread(
&p[i], sizeof(char), 1 , fpin) ;
    }


    
//write to file
    fpout = fopen("2.txt""wt") ;
    
    
for (i = 0; i < FileSize; ++i)
    
{
        fprintf(fpout, 
" %02X", p[i]) ;
    }

    
    free(p) ;
    fclose(fpout) ;
    fclose(fpin) ;
    
return 0 ;
}

2。把文本恢复到二进制文件

#include <stdio.h>
#include 
<stdlib.h>

int main()
{
    FILE 
*fpin, *fpout;
    unsigned 
char c, c0, c1 ;
    
if ((fpin = fopen("2.txt""rt")) == NULL)
    
{
        printf(
"file can not open!\n") ;
        exit(
0) ;
    }

    
    
if ((fpout = fopen("new.rar""wb")) == NULL)
    
{
        printf(
"file can not open!\n") ;
        exit(
0) ;
    }


    
while (!feof(fpin))
    
{
        
if((c0 = fgetc(fpin) - '0'>= 10)
            c0 
-= 7 ;  /*7='A'-'0'-10*/
        
        
if(feof(fpin)) 
            
break ;     /*文件尾前还有个'\0'字符串结束标志*/
        
        
if((c1 = fgetc(fpin) - '0'>= 10)
            c1 
-= 7 ;
        
        c 
= (c0 << 4+ c1 ;
        
        fwrite(
&c, 11, fpout) ;      /*也可以用fprintf(fpout, "%c", c) ;*/
    }


    fclose(fpin) ;
    fclose(fpout) ;
    
return 0 ;
}

抱歉!评论已关闭.