为什么调用istream :: tellg()会影响程序的行为? [英] Why does calling istream::tellg() affect the behavior of my program?

查看:118
本文介绍了为什么调用istream :: tellg()会影响程序的行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将24位位图图像转换为灰度图像.

I am trying to convert a 24 bit bitmap image into grayscale.

#include<iostream>
#include<fstream>
#include<conio.h>
#include<stdio.h>
using namespace std;
class pixel{
            public:
                   unsigned char b;
                   unsigned char g;
                   unsigned char r;
            void display()
            {
                 cout<<r<<" "<<g<<" "<<b<<" ";
                 }
      }p1;
using namespace std;
int main(){
    unsigned char avg;
    fstream file("image.bmp",ios::binary|ios::in|ios::out);

    int start;
    file.seekg(10);
    file.read((char*)&start,4);


    file.seekg(start);
    int i=0;
   while(!file.eof()){
                      cout<<file.tellg();//Remove this and the program doesn't work!
                     file.read((char*)&p1,3);
                     avg=(p1.b+p1.g+p1.r)/3;
                     p1.b=avg;
                     p1.g=avg;
                     p1.r=avg;
                     file.seekg(-3,ios::cur);
                     file.write((char*)&p1,3);
                       }
    file.close();
    getch();
    return 0;
}

当我删除cout tellg语句时,循环仅运行两次!

When I remove the cout tellg statement the loop runs only two times!

我不知道删除cout语句有什么区别?

I don't understand what difference removing a cout statement make?

结果:灰度只有一个像素.

Result: Only one pixel changes to grayscale.

我在这里找到了问题的更简单版本

I found a simpler version of my problem here

同时读取和写入文件?

但是没有找到解决方案...

But didnt find a solution...

推荐答案

读写std::fstream时,在读写之间切换时需要查找.这样做的原因是文件流共享一个公共的输入和输出位置.为了也支持有效的缓冲,必须将当前位置告知相应的其他缓冲.这是寻求工作的一部分. tellg()搜索当前位置.

When reading and writing a std::fstream you need a seek when switching between reading and writing. The reason for this is that file streams share a common input and output position. To also support efficient buffering it is necessary to inform the respective other buffer about the current position. This is part of what the seek does. tellg() does a seek to the current position.

请注意,在读写之间切换是非常低效的,尤其是在实现得到优化的情况下.您最好写一个不同的文件或以合理大小的组更新值.

Note, that it is very inefficient to switch between reading and writing, especially when the implementation is well optimized. You'd be much better off either writing a different file or updating values in reasonable sized groups.

这篇关于为什么调用istream :: tellg()会影响程序的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆