使用fwrite()& fread()用于二进制输入/输出 [英] using fwrite() & fread() for binary in/output

查看:107
本文介绍了使用fwrite()& fread()用于二进制输入/输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用了大量的浮点数.经过很多摆弄后,我设法将其写入二进制文件.在以后打开该文件时,读取过程仅读取少数几个浮点数(根据fread()的返回值,所有值均为0.0f).该读数应该将浮点数放入(原始)数组中,并且不包含原始值. 我正在使用Code :: Blocks和MinGW在64位PC上的32位领域中编写程序..我对c/c ++和指针不是很熟练.

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 ) ;
    ...
}

推荐答案

不是写入二进制文件或从中读取二进制文件,而是将这些文件作为文本文件打开.

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

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

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

outFile = fopen( chN  , "wb" ) ;

这篇关于使用fwrite()&amp; fread()用于二进制输入/输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆