簡體   English   中英

fstream在沒有讀取位圖的情況下跳過字符

[英]fstream skipping characters without reading in bitmap

我正在嘗試使用fstream讀取bmp文件。 但是它會跳過08和0E(十六進制)之間的值,例如,對於值42 4d 8a 16 0b 00 00 00 00 00 36

它讀

42 4d 8a 16 00 00 00 00 00 36

跳過0b就好像它甚至不存在於文檔中。

該怎么辦?

碼:

ifstream in;
in.open("ben.bmp", ios::binary);
unsigned char a='\0';
ofstream f("s.txt");
while(!in.eof())
{
    in>>a;
    f<<a;
}

編輯:使用in.read(a,1); 而不是in>>a; 解決了讀取問題,但我需要寫無符號字符和f.write(a,1); 不接受未簽名的字符。 有沒有人用無符號字符進行寫作?

如果要一次讀取一個字節的文件,這對istream緩沖區迭代器很有用。

int main()
{
   ifstream in("ben.bmp", ios::binary);  
   ofstream f("s.txt");  

   //
   // Note: this is NOT istream_iterator
   // The major different is that the istreambuf_iterator does not skip white space.
   //
   std::istreambuf_iterator<char>  loop(in);
   std::istreambuf_iterator<char>  end;

   for(; loop != end; ++loop)
   {
       f << (*loop);  
   }

   // You could now also use it with any of the std algorithms
       // Alternative to Copy input to output
            std::copy(loop,end,std::ostream_iterator<char>(f));

       // Alternative if you want to do some processing on each element
       // The HighGain_FrequencyIvertModulator is a functor that will manipulate each char.
            std::transform( loop,
                            end,
                            std::ostream_iterator<char>(f),
                            HighGain_FrequencyIvertModulator()
                          );
}  

幾個問題:

while(!in.eof())
{
    in>>a;
    f<<a;
}

不是讀取文件的正確方法 - 您需要檢查讀取是否有效:

while( in >> a)
{
    f<<a;
}

其次,如果要以二進制模式讀取文件,則需要使用read()和相關函數 - 無論文件在何種模式下打開,>>運算符始終執行格式化(非二進制)輸入。

編輯:寫需要一個演員:

unsigned char c = 42;
out.write( (char *) & c, 1 );

operator>>operator<<設計用於文本輸入和輸出。

對於二進制文件,使用read()write()

這是因為流將字節解釋為ascii字符。 08到0e是白色空格(水平制表符,換行符,垂直制表符,回車符等),它們被跳過。 像其他答案所說,你需要使用流的read()方法。

#include <fstream>
#include <iostream>
#include <string>

int main(int argc, char *argv[])
{
  const char *bitmap;
  const char *output = "s.txt";

  if (argc < 2)
    bitmap = "ben.bmp";
  else
    bitmap = argv[1];

  std::ifstream  in(bitmap, std::ios::in  | std::ios::binary);
  std::ofstream out(output, std::ios::out | std::ios::binary);
  char a;

  while (in.read(&a, 1) && out.write(&a, 1))
    ;

  if (!in.eof() && in.fail())
    std::cerr << "Error reading from " << bitmap << std::endl;

  if (!out)
    std::cerr << "Error writing to "   << output << std::endl;

  return 0;
}

處理二進制數據時,使用read()而不是重載的按位運算符(<<和>>)

如果您需要使用流,可以執行以下操作:

std::ifstream ifs("bar", std::ios::in | std::ios::binary);
std::ofstream ofs("foo", std::ios::out | std::ios::binary);
ofs << ifs.rdbuf();

確保將其打開為二進制文件,如下所示:

ifstream ifs('input.bin', ios::in | ios::binary);

ofstream ofs('output.bin', ios::out | ios::binary);

檢查ifs.good()以確保打開的文件一切正常也是一個好習慣

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM