A program that copies a file and then outputs the copy in binary formate

This is a discussion on A program that copies a file and then outputs the copy in binary formate within the C++ Programming forums, part of the General Programming Boards category; For copying a file I've used this code: #include <fstream> int main() { std::ifstream file("C:/Kopia.dat"); std::ofstream file2("C:/KopiaAvKopia.dat"); int x = ...

  1. #1
    Registered User
    Join Date
    Dec 2001
    Posts
    367

    A program that copies a file and then outputs the copy in binary formate

    For copying a file I've used this code:


    #include <fstream>

    int main()
    {
    std::ifstream file("C:/Kopia.dat");
    std::ofstream file2("C:/KopiaAvKopia.dat");

    int x = sizeof file;

    char c[x];
    file >> c;

    file2 << c;

    return 0;

    }


    The problem here is that the program only reads the first characters before a space comes from "file" into the "c"-array. Thus, it only copies those characters into "file2".

    What I'm asking for is help with this copying process, so that it can copy everything from "file". I also would like the copied characters to be outputted in binary formate to "file2".

  2. #2
    S­énior Member
    Join Date
    Jan 2002
    Posts
    982
    You need to open the files in binary mode. Try something like -

    Code:
    #include <fstream>
    
    using namespace std;
    
    int main()
    {	
    	ifstream in("C:/Kopia.dat",ios::binary);
    	ofstream out("C:/KopiaAvKopia.dat",ios::binary);
    
    	out << in.rdbuf();
    
    	return 0;
    }

  3. #3
    I'm Back
    Join Date
    Dec 2001
    Posts
    556
    If what Sorensen says doesn't do what you want, then heres few things that i would try...


    >>int x = sizeof file;

    should be int x=sizeof(file);

    >> && << ignore spaces and '\n'
    use get/put


    PS keep the ios::binary mode that Sorensen suggests.

  4. #4
    S­énior Member
    Join Date
    Jan 2002
    Posts
    982
    >>int x = sizeof file;

    should be int x=sizeof(file);
    First off, you only need parentheses with primitive types. Secondly you can't use sizeof to get the length of files, it'll return the sizeof the ifstream object. Thirdly, even if it did return the length of the file (or you obtained it by some other method such as ifstream::seekg() and ifstream::tellg()), initialising a stack based array with a variable is not legal C++ (although some compilers let you do it). You'd need to dynamically allocate memory or use something like a std::vector.

    >> && << ignore spaces and '\n'
    use get/put
    If you were reading/writing in binary mode, you'd use fstream::read() and fstream::write(), not get/put.

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21