program tip

바이너리 파일 읽기 및 쓰기

radiobox 2020. 9. 3. 08:13
반응형

바이너리 파일 읽기 및 쓰기


바이너리 파일을 버퍼로 읽은 다음 버퍼를 다른 파일에 쓰는 코드를 작성하려고합니다. 다음 코드가 있지만 버퍼는 파일의 첫 번째 줄에서 두 개의 ASCII 문자 만 저장하고 다른 것은 저장하지 않습니다.

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 );

이 작업을 C ++ 방식으로 수행하려면 다음과 같이하십시오.

#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));
}

수정하기 위해 버퍼에 해당 데이터가 필요한 경우 다음을 수행하십시오.

#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), {});

}

 sizeof(buffer) == sizeof(char*) 

대신 길이를 사용하십시오.

또한 fopen" wb" 와 함께 사용 하는 것이 좋습니다 ....


다음은 rdbuf. 나는 이것을 웹에서 얻었다. 여기에서 내 원본을 찾을 수 없습니다.

#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;
}

sizeof (buffer)는 버퍼의 실제 크기가 아니라 마지막 줄의 포인터 크기입니다. 대신 이미 설정 한 "길이"를 사용해야합니다.


sizeof (buffer) 대신 fwrite에 길이를 전달해야합니다.


There is a much simpler way. This does not care if it is binary or text file.

Use 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];

It can be done with simple commands in the following snippet.

Copies the whole file of any size. No size constraint!

Just use this. Tested And Working!!

#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;
}

Having a smaller buffer size would be helpful in copying tiny files. Even "char buffer[2]" would do the job.

참고URL : https://stackoverflow.com/questions/5420317/reading-and-writing-binary-file

반응형