Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,948 questions

51,890 answers

573 users

How to duplicate (copy) text file in C

3 Answers

0 votes
#include <stdio.h>
#include <stdlib.h>
   
int main(int argc, char **argv) 
{ 
    FILE *f, *copy_f;
    int ch;

    f = fopen("d:\\data.txt", "r");
    copy_f = fopen("d:\\data_copy.txt", "w");
    if( !f || !copy_f)
    {
        puts("File open error");
        exit(1);
    }
    while( (ch = fgetc(f)) != EOF)
        fputc(ch, copy_f);

    puts("File duplicated");

    fclose(f);
    fclose(copy_f);

    return 0;
}
   
/*
  
run:
   
File duplicated

*/

 



answered Sep 29, 2015 by avibootz
edited Dec 22, 2015 by avibootz
0 votes
#include <stdio.h>
    
int copy_files(char *src, char *target);  
    
int main(int argc, char **argv) 
{ 
    if (copy_files("d:\\data.txt", "d:\\data_copy.txt"))
        puts("File duplicated");
    else
        puts("File open error");
 
    return 0;
}
 
int copy_files(char *src, char *target)
{
    FILE *f, *copy_f;
    int ch;
 
    f = fopen(src, "r");
    copy_f = fopen(target, "w");
    if( !f || !copy_f)
        return 0;
     
    while( (ch = fgetc(f)) != EOF)
        fputc(ch, copy_f); 

    fclose(f);
    fclose(copy_f);
     
    return 1;
}
    
/*
   
run:
    
File duplicated
 
*/

 



answered Sep 29, 2015 by avibootz
edited Dec 22, 2015 by avibootz
0 votes
#include <stdio.h>
#include <unistd.h>
    
int copy_files(char *src, char *target);  
    
int main(int argc, char **argv) 
{ 
    if (copy_files("d:\\data.txt", "d:\\data_copy.txt"))
        puts("File duplicated\n");
    else
        puts("File didn't duplicated\n");
 
    return 0;
}
 
int copy_files(char *src, char *target)
{
    FILE *f, *copy_f;
    int ch;
 
    if ( access( src, F_OK ) == -1 ) {
        printf("file %s doesn't exist\n", src);
        return 0;
    }
    f = fopen(src, "r");
    copy_f = fopen(target, "w");
    if( !f || !copy_f)
        return 0;
     
    while( (ch = fgetc(f)) != EOF)
        fputc(ch, copy_f); 

    fclose(f);
    fclose(copy_f);
     
    return 1;
}
    
/*
   
run:
    
file d:\data.txt doesn't exist
File didn't duplicated
 
*/

 



answered Dec 21, 2015 by avibootz
edited Dec 22, 2015 by avibootz

Related questions

2 answers 225 views
1 answer 129 views
129 views asked Dec 26, 2020 by avibootz
1 answer 132 views
132 views asked Dec 26, 2020 by avibootz
1 answer 142 views
3 answers 300 views
1 answer 83 views
...