EnviWrite.h 1.6 KB
#ifndef ENVIWRITE_H
#define ENVIWRITE_H
#include <fstream>
#include <stdio.h>
#include "EnviHeader.h"
#include "EnviFid.h"
#include "EnviOpen.h"

// Take a memory pointer, and copy all of that data to disk.
static int EnviWrite(float* ptr, int npixels, EnviFidClass &fid)
{
    if(fid.mode == "r") return 0;

	//open a binary file for writing
    if (fid.file == NULL)
    {
        cout<<"Binary file isn't open."<<endl;
        return 1;
    }

    //allocate an array of zeros equal to the size of a single pixel
    float* zeroPtr = (float*) malloc(sizeof(float) * fid.header.nF);
    memset(zeroPtr, 0, sizeof(float) * fid.header.nF);


    int j = 0;
    //for each pixel send to the EnviRead function
    for(int p = 0; p<npixels; p++)
    {

        //while the mask is zero
        while(fid.mask[fid.filePos] == 0)
        {
            //increment filePos
            fid.filePos++;
            fid.header.sX++;
            j++;

            //write a sequence of zeros
            size_t results= fwrite(zeroPtr, sizeof(float), fid.header.nF, fid.file);
            //check for errors
            if (results != fid.header.nF)
            {
                cout<<"Error during read # "<<j<<endl;
                return 0;
            }
        }

        //write a pixel
        size_t results= fwrite(&ptr[fid.header.nF * p], sizeof(float), fid.header.nF, fid.file);
        if (results != fid.header.nF)
        {
            cout<<"Error during read # "<<j<<endl;
            return 0;
        }

        //increment filePos
        fid.filePos++;
        fid.header.sX++;
        j++;
    }

    return j;

}





#endif