hi all,
i have a caputure file ( *.cap) i open it in binary mode , now i nead 2 make an outfile , also *.cap
i gave the outfile 2 my prog. out.cap, it works and i became no errors, but when i tried 2 open it , it doesn't work.

i made nothing in the prog.
string infile,outfile;
char arr[10];
int i;
void main ()
{

cout<<"Enter your input filename"<<endl;
cin>>infile;
ifstream myinfile;
myinfile.open(infile.c_str(), ios::binary );
cout<<"Enter your output filename"<<endl;
cin>>outfile;
ofstream myoutfile(outfile.c_str());
for(i=0;i<10;i++)
{
myinfile>>arr;
myoutfile<<arr<<endl;
}

Dani AI

Generated

A concise diagnosis and a safe fix that builds on 's suggestion:

The problem is not just the output-file flag — it is using text/formatted I/O on a binary file. Formatted extraction (operator>>) and insertion (operator<< plus endl) will treat whitespace, stop at null bytes and (on Windows) translate line endings. That corrupts any .cap/pcap packet file. Correct approach: open both streams with std::ios::binary and copy raw bytes with unformatted I/O (read/write) or a binary-safe convenience method.

Example binary-safe copy (check opens and return codes in real code):

#include <fstream>

int main()
{
    std::ifstream in("in.cap", std::ios::binary);
    if (!in) return 1;
    std::ofstream out("out.cap", std::ios::binary);
    if (!out) return 1;

    char buf[4096];
    while (in.read(buf, sizeof(buf)) || in.gcount() > 0)
        out.write(buf, in.gcount());

    return 0;
}

Notes and troubleshooting:

  • out << in.rdbuf(); is a shorter, binary-safe one-liner for copying streams.
  • On modern C++ use std::filesystem::copy_file when available.
  • Verify success by comparing file sizes or checksums. Inspect the first bytes to confirm a pcap header: classic libpcap magic is 0xa1b2c3d4 or 0xd4c3b2a1; pcap-ng starts with 0x0A0D0D0A.
  • Use int main() (not void main()), check stream state after open, and handle filenames that contain spaces (use std::getline).

Acknowledgements: was correct to point out binary mode; ’s reminder about posting code with code tags helps others diagnose issues more quickly.

Recommended Answers

All 3 Replies

>but when i tried 2 open it , it doesn't work.
You're reading from a binary oriented file stream but writing to a text oriented file stream. Most likely you want to open the output stream as binary also.

And please don't use chatty abbreviations. We have a rule against that because it makes posts less professional and more difficult to understand.

sorry for using the chatty words,
now shall i open may output file also in binary mode and write on it?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.