使用fwrite()& fread()用于二进制输入/输出

时间:2014-01-19 11:31:18

标签: c++ binary fwrite fread

我正在使用大量的花车。经过大量的摆弄后,我设法将其写入二进制文件。在稍后打开该文件时,读取过程只读取几个浮点数(根据fread()的返回值,并且它的值都是0.0f)。读取应该将浮点数放入(原始)数组中,并且它不包含原始值。 我正在使用Code :: Blocks和MinGW在64位PC上的32位域中执行程序..而且我对c / c ++和指针不是很精通。

#include<...>

const int mSIZE = 6000 ;
static float data[mSIZE*mSIZE] ;

void myUseFunc(){
    const char *chN = "J:/path/flt_632_55.bin" ;
    FILE *outFile=NULL ;
    # .. sucessfully filling and using data[]
    ..
    size_t st = mSIZE*mSIZE ;
    outFile = fopen( chN  , "w" ) ;
    if(!outFile){ printf("error opening file %s \n", chN); exit(0);}
    else{ 
        size_t indt;
        indt = fwrite( data , sizeof(float), st , outFile );
        std::cout << "floats written to file: " << indt << std::endl ;
        #.. value shows that all values ar written
        # and a properly sized file has appeared at the proper place
    }
    fclose( outFile ) ; 
}

void myLoadFunc( const char *fileName){
    FILE *inFile = NULL ;
    inFile = fopen( fileName, "r");
    if(!inFile){ printf("error opening file %s \n", fileName); exit(0); }
    size_t blok = mSIZE*mSIZE ;
    size_t out;
    out = fread( dataOne, sizeof(GLfloat), blok , inFile);
    fclose(inFile);
    if(out != blok){
        std::cout<< out << std::endl ;
        fputs ("Reading error",stderr);
        # no stderr presented at the console ..
        printf("some error\n") ;
        exit(0);
        # .. program exits at out=14
    }
    ...
}

int main( ){
    ...
    const char *FileName = "J:/path/flt_632_55.bin" ;
    myLoadFunc( FileName ) ;
    ...
}

1 个答案:

答案 0 :(得分:1)

写入/读取二进制文件,您将文件作为文本文件打开。

您需要将"b"添加到打开模式,例如

outFile = fopen( chN  , "wb" ) ;