繁体   English   中英

使用 fwrite() 和 fread() 进行二进制输入/输出

[英]using fwrite() & fread() for binary in/output

我正在使用大量的浮点数。 经过大量摆弄后,我设法将其写入二进制文件。 稍后打开该文件时,读取过程仅读取少量浮点数(根据 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 ) ;
    ...
}

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

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

outFile = fopen( chN  , "wb" ) ;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM