Domanda

I have a .dat file with ASCII characters like following picture:

enter image description here

It is basically a series of 16-bit numbers. I can read it, as unsigned short, in my data structure, but I have no idea how to save my unsigned short as same format as the input. Here is my current code, although the value is right, the format is not. See following picture:

enter image description here

Anyone has any idea how I should save it same as the input format? Here is my saving function"

void SavePxlShort(vector<Point3D> &pts, char * fileName)
{
    ofstream os(fileName, ios::out);

    size_t L = pts.size();
    cout << "writing data (pixel as short) with length "<< L << " ......" << endl;

    unsigned short pxl;
    for (long i = 0; i < L; i++)
    {
        pxl = Round(pts[i].val());
        if (pts[i].val() < USHRT_MAX)
        {
            os <<  pxl << endl;
        }
        else
        {
            cout << "pixel intensity overflow ushort" << endl;
            return;
        }
    }

    os.close();

    return;
}
È stato utile?

Soluzione

void SavePxlShort(vector<Point3D> &pts, char * fileName)
{
    ofstream os(fileName, ios::out, ios::binary);

    size_t L = pts.size();
    cout << "writing data (pixel as short) with length "<< L << " ......" << endl;

    unsigned short* pData = new unsigned short[L];
    unsigned short pxl;
    for (long i = 0; i < L; i++)
    {
        pxl = pts[i].val();
        if (pts[i].val() < USHRT_MAX)
        {
            pData[i] = pxl ;
        }
        else
        {
            cout << "pixel intensity overflow ushort" << endl;
            return;
        }
    }

    os.write(reinterpret_cast<char*> (pData), sizeof(unsigned short)*L);
    os.close();

    delete pData;

    return;
}

Altri suggerimenti

Two things:

  1. You are are not opening the stream in binary mode. Try this:

    ofstream os(fileName, ios::out | ios::binary);
    

    Actually, because ofstream automatically sets the ios::out flag, you just need this:

    ofstream os(fileName, ios::binary);
    
  2. Another problem is that you are calling std::endl. This outputs a \n and then flushes the stream.

    os <<  pxl << endl;
    

    Change the above to just:

    os <<  pxl;
    

in place of

os << pxl << endl;

You could put

os.write((char*)&pxl, sizeof(pxl));

to write the raw bytes of pxl into the file instead of the ASCII representation. Bear in mind the byte order and word size of an unsigned short may vary between systems.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top