using fwrite() & fread() for binary in/output

本小妞迷上赌 提交于 2019-12-04 06:40:04

问题


I'm using a large array of floats. After a lot of fiddling I've managed to write it to a binary file. When opening that file at a later time, the reading process only reads a couple of handfuls of floats (according to the return-value of fread(), and it's all values 0.0f). The reading is supposed to put the floats into an (the original) array, and it does not contain the original values. I'm using Code::Blocks and MinGW doing a program in the 32bit realm on a 64bit pc .. and I'm not very proficient on c/c++ and pointers.

#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:


You are not writing to/reading from a binary file, you open the files as text files.

You need to add the "b" to the open mode, like

outFile = fopen( chN  , "wb" ) ;


来源:https://stackoverflow.com/questions/21216164/using-fwrite-fread-for-binary-in-output

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!