copy file

How can i copy output of this dna1.dat file and copy the value inside a new file dna2.dat?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () 
{
  FILE *outputfile;
  outputfile=fopen("dna1.dat","w");
  if(outputfile!=NULL)
  {
                      cout<<"Reading DNA sequences from dna1.dat..."<<endl;
                      cout<<"ATGCCTGAGA"<<endl;
                      cout<<"ACCTGACA"<<endl;
                      cout<<"ATCCTGAC"<<endl;
                              
                      fclose(outputfile);
  }
  else{cout<<"can't";}
  system("pause");
  return 0;
}
Using a pointer to file(FILE*)...C? why not std::fstream. I can give you an example on that, if you want it.

Aceix.
yeah, definitely,actually i didn't learn about std::fstream ,so i couldn't use that :(
Last edited on
If you just want to make an exact copy of the contents of a file into a new file, something like this should work:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
    FILE * infile;
    FILE * outfile;

    infile  = fopen(srcfilename,  "rb");
    outfile = fopen(destfilename, "wb");

    filecopy(outfile, infile);
    
    fclose(infile);
    fclose(outfile);

void filecopy(FILE *dest, FILE *src)
{
    const int size = 16384; 
    char buffer[size];

    while (!feof(src))
    {
        int n = fread(buffer, 1, size, src);
        fwrite(buffer, 1, n, dest);
    }

}
Thank you Chervil
here you go:
1
2
3
4
5
6
7
8
9
10
fstream file;
file.open("infile.txt",ios::ate); //opens a file, infile.txt and sets the "cursor" to the end
char* data=new char[1024];
int size=file.tellg(); //get the size of the file(no of bytes to copy)
file.seekg(0); //set the get pointer to the beginning
file.read(data,size);//copy size(all) data into the buffer called data
file.close();
file.open("outfile.txt",ios::beg);//open outfile.txt to copy data to
file.write(data,size);//also writes all charactes in data to the outfile.txt
file.close();


For more info:
http://cplusplus.com/doc/tutorial/files/
http://cplusplus.com/reference/fstream/fstream/

Aceix.
Thank u very much Aceix.
if you want to save a line of code you can do this instead
fstream file("infile.txt");
Topic archived. No new replies allowed.