c++ - C++ 中的 .dat ASCII 文件 I/O

标签 c++ file file-io ascii

我有一个带有 ASCII 字符的 .dat 文件,如下图所示:

enter image description here

它基本上是一系列 16 位数字。我可以在我的数据结构中以无符号短整型的形式读取它,但我不知道如何将我的无符号短整型保存为与输入相同的格式。这是我当前的代码,虽然值是正确的,但格式不是。见下图:

enter image description here

有人知道我应该如何将其保存为输入格式吗?这是我的保存功能”

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

最佳答案

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

关于c++ - C++ 中的 .dat ASCII 文件 I/O,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21841379/

相关文章:

c - 读取为未缓存的直接 I/O 打开的文件的最后一个 block 不会产生 EOF,正常行为?

java - 在 XSLT 之前替换 XML 中的文本

c++ - `if(CONSTANT) { ... }` 是否在 C/C++ 中进行了优化?

c - 如何使用c代码查找文件的尾部

php - 从文本文件中删除空行

c - 存档的应用程序无法打开文本文件,但从 Xcode 成功打开

C# 使用大型多维(非锯齿状)字节数组执行文件 I/O 的简单方法

c++ - 如何从 ifstream 获取格式化输入

c++ - 对于 C++ 程序员来说,哪个是最好的 Linux 程序?

c++ - InDev 基于位的加密程序中未知的 C++ 堆损坏,C++ 编程的新手