Hướng dẫn fstream read binary file c++ - fstream đọc tệp nhị phân c ++

Tôi đang cố viết mã để đọc một tệp nhị phân vào bộ đệm, sau đó viết bộ đệm vào một tệp khác. Tôi có mã sau, nhưng bộ đệm chỉ lưu trữ một vài ký tự ASCII từ dòng đầu tiên trong tệp và không có gì khác.

int length;
char * buffer;

ifstream is;
is.open ("C:\\Final.gif", ios::binary );
// get length of file:
is.seekg (0, ios::end);
length = is.tellg();
is.seekg (0, ios::beg);
// allocate memory:
buffer = new char [length];
// read data as a block:
is.read (buffer,length);
is.close();

FILE *pFile;
pFile = fopen ("C:\\myfile.gif", "w");
fwrite (buffer , 1 , sizeof(buffer) , pFile );

Hướng dẫn fstream read binary file c++ - fstream đọc tệp nhị phân c ++

Gsamara

70.5K41 Huy hiệu vàng182 Huy hiệu bạc288 Huy hiệu đồng41 gold badges182 silver badges288 bronze badges

Đã hỏi ngày 24 tháng 3 năm 2011 lúc 14:00Mar 24, 2011 at 14:00

2

Nếu bạn muốn làm điều này theo cách C ++, hãy làm như vậy:

#include <fstream>
#include <iterator>
#include <algorithm>

int main()
{
    std::ifstream input( "C:\\Final.gif", std::ios::binary );
    std::ofstream output( "C:\\myfile.gif", std::ios::binary );

    std::copy( 
        std::istreambuf_iterator<char>(input), 
        std::istreambuf_iterator<char>( ),
        std::ostreambuf_iterator<char>(output));
}

Nếu bạn cần dữ liệu đó trong bộ đệm để sửa đổi nó hoặc một cái gì đó, hãy làm điều này:

#include <fstream>
#include <iterator>
#include <vector>

int main()
{
    std::ifstream input( "C:\\Final.gif", std::ios::binary );

    // copies all data into buffer
    std::vector<unsigned char> buffer(std::istreambuf_iterator<char>(input), {});

}

Hướng dẫn fstream read binary file c++ - fstream đọc tệp nhị phân c ++

Đã trả lời ngày 24 tháng 3 năm 2011 lúc 14:19Mar 24, 2011 at 14:19

Bjorn Pollexbjorn PollexBjörn Pollex

73,8K28 Huy hiệu vàng193 Huy hiệu bạc278 Huy hiệu đồng28 gold badges193 silver badges278 bronze badges

10

Dưới đây là một ví dụ ngắn, cách C ++ sử dụng rdbuf. Tôi đã nhận được điều này từ web. Tôi không thể tìm thấy nguồn gốc của mình về điều này:

#include <fstream>
#include <iostream>

int main () 
{
  std::ifstream f1 ("C:\\me.txt",std::fstream::binary);

  std::ofstream f2 ("C:\\me2.doc",std::fstream::trunc|std::fstream::binary);

  f2<<f1.rdbuf();

  return 0;
}

Đã trả lời ngày 24 tháng 3 năm 2011 lúc 17:07Mar 24, 2011 at 17:07

Thomas Matthewsthomas MatthewsThomas Matthews

55,9K16 Huy hiệu vàng97 Huy hiệu bạc151 Huy hiệu Đồng16 gold badges97 silver badges151 bronze badges

1

 sizeof(buffer) == sizeof(char*) 

Sử dụng chiều dài thay thế.

Ngoài ra, tốt hơn là sử dụng

#include <fstream>
#include <iterator>
#include <algorithm>

int main()
{
    std::ifstream input( "C:\\Final.gif", std::ios::binary );
    std::ofstream output( "C:\\myfile.gif", std::ios::binary );

    std::copy( 
        std::istreambuf_iterator<char>(input), 
        std::istreambuf_iterator<char>( ),
        std::ostreambuf_iterator<char>(output));
}
0 với "________ 11" ....

Hướng dẫn fstream read binary file c++ - fstream đọc tệp nhị phân c ++

Nullpoi

55,7K22 Huy hiệu vàng125 Huy hiệu bạc143 Huy hiệu đồng22 gold badges125 silver badges143 bronze badges

Đã trả lời ngày 24 tháng 3 năm 2011 lúc 14:03Mar 24, 2011 at 14:03

Hướng dẫn fstream read binary file c++ - fstream đọc tệp nhị phân c ++

2

sizeof (bộ đệm) là kích thước của một con trỏ trên dòng cuối cùng của bạn không phải là kích thước thực tế của bộ đệm. Bạn cần sử dụng "độ dài" mà bạn đã thiết lập thay thế

Đã trả lời ngày 24 tháng 3 năm 2011 lúc 14:01Mar 24, 2011 at 14:01

Jcoderjcoderjcoder

29.2K19 Huy hiệu vàng85 Huy hiệu bạc127 Huy hiệu đồng19 gold badges85 silver badges127 bronze badges

Bạn nên chuyển độ dài vào fwrite thay vì sizeof (bộ đệm).

Đã trả lời ngày 24 tháng 3 năm 2011 lúc 14:02Mar 24, 2011 at 14:02

retrodroneretrodroneretrodrone

5.7709 Huy hiệu vàng37 Huy hiệu bạc65 Huy hiệu Đồng9 gold badges37 silver badges65 bronze badges

Dưới đây là triển khai C ++ 14 tiêu chuẩn bằng cách sử dụng các vectơ và bộ dữ liệu để đọc và viết

#include <fstream>
#include <iterator>
#include <algorithm>

int main()
{
    std::ifstream input( "C:\\Final.gif", std::ios::binary );
    std::ofstream output( "C:\\myfile.gif", std::ios::binary );

    std::copy( 
        std::istreambuf_iterator<char>(input), 
        std::istreambuf_iterator<char>( ),
        std::ostreambuf_iterator<char>(output));
}
2.vectors and tuples to Read and Write
#include <fstream>
#include <iterator>
#include <algorithm>

int main()
{
    std::ifstream input( "C:\\Final.gif", std::ios::binary );
    std::ofstream output( "C:\\myfile.gif", std::ios::binary );

    std::copy( 
        std::istreambuf_iterator<char>(input), 
        std::istreambuf_iterator<char>( ),
        std::ostreambuf_iterator<char>(output));
}
2.

Mã đoạn trích:

try {
if (file_type == BINARY_FILE) {

    /*Open the stream in binary mode.*/
    std::ifstream bin_file(file_name, std::ios::binary);

    if (bin_file.good()) {
        /*Read Binary data using streambuffer iterators.*/
        std::vector<uint8_t> v_buf((std::istreambuf_iterator<char>(bin_file)), (std::istreambuf_iterator<char>()));
        vec_buf = v_buf;
        bin_file.close();
    }

    else {
        throw std::exception();
    }

}

else if (file_type == ASCII_FILE) {

    /*Open the stream in default mode.*/
    std::ifstream ascii_file(file_name);
    string ascii_data;

    if (ascii_file.good()) {
        /*Read ASCII data using getline*/
        while (getline(ascii_file, ascii_data))
            str_buf += ascii_data + "\n";

        ascii_file.close();
    }
    else {
        throw std::exception();
    }
}

else if (file_type == HEX_FILE) {

    /*Open the stream in default mode.*/
    std::ifstream hex_file(file_name);

    if (hex_file.good()) {
        /*Read Hex data using streambuffer iterators.*/
        std::vector<char> h_buf((std::istreambuf_iterator<char>(hex_file)), (std::istreambuf_iterator<char>()));
        string hex_str_buf(h_buf.begin(), h_buf.end());
        hex_buf = hex_str_buf;

        hex_file.close();
    }
    else {
        throw std::exception();
    }
}

}

Mã nguồn đầy đủ có thể được tìm thấy ở đây

Đã trả lời ngày 4 tháng 2 năm 2021 lúc 2:10Feb 4, 2021 at 2:10

Hướng dẫn fstream read binary file c++ - fstream đọc tệp nhị phân c ++

Haseeb Mirhaseeb MirHaseeb Mir

8611 Huy hiệu vàng13 Huy hiệu bạc21 Huy hiệu đồng1 gold badge13 silver badges21 bronze badges

Có một cách đơn giản hơn nhiều. Điều này không quan tâm nếu đó là tệp nhị phân hoặc văn bản.

Sử dụng noskipws.

char buf[SZ];
ifstream f("file");
int i;
for(i=0; f >> noskipws >> buffer[i]; i++);
ofstream f2("writeto");
for(int j=0; j < i; j++) f2 << noskipws << buffer[j];

Hoặc bạn chỉ có thể sử dụng chuỗi thay vì bộ đệm.

string s; char c;
ifstream f("image.jpg");
while(f >> noskipws >> c) s += c;
ofstream f2("copy.jpg");
f2 << s;

Thông thường truyền phát bỏ các ký tự không gian trắng như Space hoặc New Line, Tab và tất cả các ký tự điều khiển khác. Nhưng noskipws làm cho tất cả các nhân vật được chuyển giao. Vì vậy, điều này sẽ không chỉ sao chép một tệp văn bản mà còn là một tệp nhị phân. Và Stream sử dụng bộ đệm bên trong, tôi cho rằng tốc độ sẽ không chậm.

Đã trả lời ngày 10 tháng 5 năm 2018 lúc 1:14May 10, 2018 at 1:14

Hướng dẫn fstream read binary file c++ - fstream đọc tệp nhị phân c ++

ZetazetaZeta

8919 Huy hiệu bạc23 Huy hiệu Đồng9 silver badges23 bronze badges

1

Nó có thể được thực hiện với các lệnh đơn giản trong đoạn trích sau đây.

Sao chép toàn bộ tập tin của bất kỳ kích thước. Không bị ràng buộc kích thước!

Chỉ cần sử dụng điều này. Đã thử nghiệm và làm việc !!

#include<iostream>
#include<fstream>
using namespace std;
int main()
{
  ifstream infile;
  infile.open("source.pdf",ios::binary|ios::in);

  ofstream outfile;
  outfile.open("temppdf.pdf",ios::binary|ios::out);

  int buffer[2];
  while(infile.read((char *)&buffer,sizeof(buffer)))
  {
      outfile.write((char *)&buffer,sizeof(buffer));
  }

  infile.close();
  outfile.close();
  return 0;
}

Có kích thước bộ đệm nhỏ hơn sẽ hữu ích trong việc sao chép các tệp nhỏ. Ngay cả "bộ đệm char [2]" cũng sẽ thực hiện công việc.

Đã trả lời ngày 2 tháng 11 năm 2014 lúc 15:33Nov 2, 2014 at 15:33

imajetyhkimajetyhkiMajetyHK

1371 Huy hiệu vàng1 Huy hiệu bạc7 Huy hiệu đồng1 gold badge1 silver badge7 bronze badges

4

Chế độ nhị phân trong C ++ là gì?

Một luồng nhị phân là một chuỗi các ký tự được đặt hàng có thể ghi lại dữ liệu nội bộ một cách minh bạch. Dữ liệu được đọc từ một luồng nhị phân luôn bằng với dữ liệu trước đó được ghi ra cho luồng đó. Việc triển khai chỉ được phép nối một số ký tự null vào cuối luồng.an ordered sequence of characters that can transparently record internal data. Data read in from a binary stream always equals to the data that were earlier written out to that stream. Implementations are only allowed to append a number of null characters to the end of the stream.

Làm thế nào đọc và ghi tệp dữ liệu nhị phân trong C#?

Chúng ta có thể sử dụng lớp BinaryReader và BinaryWriter để đọc và viết các tệp nhị phân tương ứng.Trong khi tạo đối tượng của BinaryReader và BinaryWriter, chúng tôi phải chuyển đối tượng luồng dưới dạng đối số của hàm tạo.Trước tiên, chúng tôi tạo đối tượng của lớp FileStream tham chiếu đến tệp được chỉ định.make use of BinaryReader and BinaryWriter class for reading and writing binary files respectively. While creating object of BinaryReader and BinaryWriter we have to pass stream object as constructor argument. First we create the object of FileStream class which references to the specified file.

Một phương pháp thích hợp để mở tệp để viết dưới dạng tệp nhị phân là gì?

Để mở một tệp ở định dạng nhị phân, thêm 'B' vào tham số chế độ.Do đó, chế độ "RB" mở tệp ở định dạng nhị phân để đọc, trong khi chế độ "WB" mở tệp ở định dạng nhị phân để viết.add 'b' to the mode parameter. Hence the "rb" mode opens the file in binary format for reading, while the "wb" mode opens the file in binary format for writing.

Các tệp nhị phân khác nhau các tệp văn bản khác nhau trong C ++?

Các tệp văn bản được tổ chức xung quanh các dòng, mỗi dòng kết thúc bằng ký tự dòng mới ('\ n').Các tệp mã nguồn là các tệp văn bản của chính họ.Một tệp nhị phân là tệp trong đó dữ liệu được lưu trữ trong tệp giống như cách được lưu trữ trong bộ nhớ chính để xử lý.A binary file is the one in which data is stored in the file in the same way as it is stored in the main memory for processing.