2014-10-20 50 views
0

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

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

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

使用C++

+0

如何插入分隔符例如'|'或者它的两个数字中间的代码? – SajjadHashmi 2014-10-20 07:07:34

+1

这听起来像你有一个形象。为什么不把它存储为这样? – 2014-10-20 07:12:21

+0

它是扫描区域的深度(640 * 480点深度)。这是来自MS Kinect的扫描。我需要存储这个值供以后使用。 – Fox 2014-10-20 07:21:09

回答

1

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

+0

请给我举个例子吗?我正在使用C++。我真的需要将它们存储到文件中。那么我应该使用二进制文件吗?如何从中读取数字? – Fox 2014-10-20 07:17:42

+0

http://stackoverflow.com/questions/15654879/c-file-writing-reading – 2014-10-20 07:25:21

0

想必你有某种形式的数据结构的代表你的形象,这地方里面保存实际数据:

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存储底层图像数据,虽然你可能应该是),但希望这是足以让你开始。

0

您可以打印0-255之间的数字作为文件中的字符值。 请参阅下面的代码。在这个例子中,我将整数70打印为char。 所以这个结果在控制台上打印为'F'。 同样,你可以把它读为char,然后把这个char转换为整数。

#include <stdio.h> 

int main() 
{ 

    int i = 70; 
    char dig = (char)i; 

    printf("%c", dig); 

    return 0; 
} 

这样您可以限制文件大小。

相关问题