【问题标题】:.dat ASCII file I/O in C++C++ 中的 .dat ASCII 文件 I/O
【发布时间】:2014-03-17 11:24:01
【问题描述】:

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

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

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

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

【问题讨论】:

  • ASCII 定义只包含 7 位,那你怎么能有一个 16 位的块并用 ASCII 显示呢?

标签: c++ file file-io ascii


【解决方案1】:
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;
}

【讨论】:

  • 内存泄漏。你在哪里删除pData
【解决方案2】:

两件事:

  1. 您没有以二进制模式打开流。试试这个:

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

    其实,因为ofstream自动设置ios::out标志,你只需要这个:

    ofstream os(fileName, ios::binary);
    
  2. 另一个问题是你打电话给std::endl。这会输出一个\n,然后刷新流。

    os <<  pxl << endl;
    

    将上面的内容改为:

    os <<  pxl;
    

【讨论】:

  • 这会输出值的文本表示,而不是二进制表示。
【解决方案3】:

代替

os << pxl << endl;

你可以放

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

将 pxl 的原始字节写入文件而不是 ASCII 表示。请记住,无符号 short 的字节顺序和字长可能因系统而异。

【讨论】:

    猜你喜欢
    • 2011-11-20
    • 2011-08-07
    • 2023-03-08
    • 1970-01-01
    • 2011-11-25
    • 1970-01-01
    • 2015-05-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多