【问题标题】:What is the best solution for writing numbers into file and than read them?将数字写入文件而不是读取它们的最佳解决方案是什么?
【发布时间】:2014-10-20 07:02:36
【问题描述】:

我有 640*480 个号码。我需要将它们写入文件。稍后我需要阅读它们。什么是最好的解决方案?数字介于 0 - 255 之间。

对我来说,最好的解决方案是把它们写成二进制(8 位)。我将数字写入 txt 文件,现在它看起来像 1011111010111110 ..... 所以数字开始和结束的地方没有问题。

我应该如何从文件中读取它们?

使用 c++

【问题讨论】:

  • 如何插入分隔符,例如|或其各自的代码在两个数字的中间?
  • 听起来你有一个图像。为什么不这样存储呢?
  • 扫描区域深度(640*480点深度)。这是来自 MS Kinect 的扫描。我需要存储这些值以备后用。
  • 最适合什么?您最关心性能、易于调试、数据可移植性、操作系统可移植性吗?
  • 性能最佳

标签: c++ file-io binary


【解决方案1】:

将 1 和 0 等位值写入文本文件不是一个好主意。文件大小会变大 8 倍。 1 字节 = 8 位。您必须存储字节,0-255 - 是字节。所以你的文件大小将是 640*480 字节而不是 640*480*8。文本文件中的每个符号的最小大小为 1 个字节。如果您想获取位,请使用您使用的编程语言的二进制运算符。读取字节要容易得多。使用二进制文件保存数据。

【讨论】:

  • 你能举个例子吗?我正在使用 C++。我真的需要将它们存储到文件中。那么我应该使用二进制文件吗?如何从中读取数字?
【解决方案2】:

大概您有某种数据结构来表示您的图像,其中某处保存实际数据:

class pixmap
{
public:
    // stuff...
private:
    std::unique_ptr<std::uint8_t[]> data;
};

所以你可以添加一个新的构造函数,它接受一个文件名并从该文件中读取字节:

pixmap(const std::string& filename)
{
    constexpr int SIZE = 640 * 480;

    // Open an input file stream and set it to throw exceptions:
    std::ifstream file;
    file.exceptions(std::ios_base::badbit | std::ios_base::failbit);
    file.open(filename.c_str());

    // Create a unique ptr to hold the data: this will be cleaned up
    // automatically if file reading throws
    std::unique_ptr<std::uint8_t[]> temp(new std::uint8_t[SIZE]);

    // Read SIZE bytes from the file
    file.read(reinterpret_cast<char*>(temp.get()), SIZE);

    // If we get to here, the read worked, so we move the temp data we've just read
    // into where we'd like it
    data = std::move(temp); // or std::swap(data, temp) if you prefer
}

我意识到我在这里假设了一些实现细节(你可能没有使用 std::unique_ptr 来存储底层图像数据,尽管你可能应该这样做)但希望这足以让你开始。

【讨论】:

    【解决方案3】:

    您可以将 0-255 之间的数字打印为文件中的 char 值。 请参阅下面的代码。在此示例中,我将整数 70 打印为 char。 所以这导致在控制台上打印为“F”。 同样,您可以将其读取为 char,然后将此 char 转换为整数。

    #include <stdio.h>
    
    int main()
    {
    
        int i = 70;
        char dig = (char)i;
    
        printf("%c", dig);
    
        return 0;
    }
    

    这样可以限制文件大小。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-14
      相关资源
      最近更新 更多