Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/155.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 从混合数据文件中读取图像_C++_File Io_Newline - Fatal编程技术网

C++ 从混合数据文件中读取图像

C++ 从混合数据文件中读取图像,c++,file-io,newline,C++,File Io,Newline,我有一个混合数据的自定义文件。在文件的末尾有一个完整的图像,我想检索它 问题是,当我“提取”它并将其粘贴到图像文件中时,rdbuf()会给我留下一些恼人的CR LF字符,而不仅仅是原始文件中的LF字符 我已经以二进制模式打开了这两个流 using namespace std; ifstream i(f, ios::in | ios::binary); bool found = false; // Found image name string s; // S

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

问题是,当我“提取”它并将其粘贴到图像文件中时,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();
使用名称空间std;
ifstreami(f,ios::in | ios::binary);
bool found=false;//找到图像名称
字符串s;//要读取的字符串
字符串n=“”;//要检索的图像名称
而(!found){
getline(i,s);
//检查它是否是名称行
如果(s[0]='-'&&s[1]='|'&&s[2]='-'){
发现=真;
//循环通过名称X:-|-XXXX-|-
//                      0123456789
//长度:1036

对于(unsigned int j=3;j我做了一些研究,发现
解决了这个问题。这个问题是在ofstream操作期间出现的,在打开之前保存文件。因为文件保存为文本(使用CR LF)这并没有回答问题,但是
for
循环中的条件应该是
j
j我知道,起初是这样的,但不知什么原因,在测试时我发现它需要一个额外的字符,所以我将它设置为-4。仍然不知道为什么会这样。顺便说一句,感谢阅读并愿意帮助^^^测试问题:似乎getline添加了“换行符”字符转换为字符串。这就是为什么它需要转到s.length()-4实际上
运算符>>
从流中输入。以二进制方式打开文件将删除任何换行符翻译。我尝试了您的代码,但它仍然保留这些CR字符…>_<
// 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;