【问题标题】:Read image from mixed data file从混合数据文件中读取图像
【发布时间】:2014-04-24 16:26:11
【问题描述】:

我有一个包含混合数据的自定义文件。在文件的末尾有一个我想要检索的完整图像。

问题是,当我将其“提取”并粘贴到图像文件中时,rdbuf() 会留下一些烦人的 CR LF 字符,而不仅仅是原始的 LF 字符。

我已经以二进制模式打开了两个流。

using namespace std;

ifstream i(f, ios::in | ios::binary);
bool found = false;     // Found image name
string s;               // String to read to
string n = "";          // Image name to retrieve
while (!found) {
    getline(i, s);
    // Check if it's the name line
    if (s[0]=='-' && s[1]=='|' && s[2]=='-') {
        found = true;
        // Loop through name X: -|-XXXX-|-
        //                      0123456789
        //      Length: 10         3  6
        for (unsigned int j=3; j<s.length()-4; j++)
            n = n + s[j];
    }
}    
ofstream o(n.c_str(), ios::out | ios::binary);

o << i.rdbuf();

【问题讨论】:

  • 这不能回答问题,但for 循环中的条件应该是j &lt; s.length()-3j &lt;= s.length()-4
  • 我知道,一开始是这样的,但不知什么原因,在测试时我发现它占用了一个额外的字符,所以我将它设置为-4。仍然不知道为什么会这样._。顺便说一句,感谢您的阅读并愿意提供帮助^^
  • 已测试问题:似乎 getline 将“换行符”字符添加到字符串中。这就是为什么它需要去 s.length()-4

标签: c++ file-io newline


【解决方案1】:

我做了一些研究,发现 &lt;&lt; 运算符将输入视为文本,因此在 Windows 上将 \n 调整为 \r\n

使用write 方法而不是&lt;&lt; 来防止这种情况发生。

你可以这样做(替换你的最后一行代码):

// get pointer to associated buffer object
std::filebuf* pbuf = i.rdbuf();
// next operations will calculate file size
// get current position
const std::size_t current = i.tellg();
// move to the end of file
i.seekg(0, i.end);
// get size of file (current position of the end)
std::size_t size = i.tellg();
// get size of remaining data (removing the current position from the size)
size -= current;
// move back to where we were
i.seekg(current, i.beg);
// allocate memory to contain image data
char* buffer=new char[size];
// get image data
pbuf->sgetn (buffer,size);
// close input stream
i.close();
// write buffer to output
o.write(buffer,size);
// free memory
delete[] buffer;  

【讨论】:

  • 实际上operator&gt;&gt; 来自流的输入。以 binary 格式打开文件将删除所有换行符翻译。
  • 我试过你的代码,但它仍然留下那些 CR 字符...>_link
【解决方案2】:

解决了。问题是在ofstream操作过程中在打开文件之前保存文件。因为文件被保存为文本(使用 CR LF),所以它也以文本形式打开。

【讨论】:

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