1. 程式人生 > 其它 >c語言中實現檔案的複製(文字複製和二進位制複製)

c語言中實現檔案的複製(文字複製和二進位制複製)

1、文字複製 fgetc、fputc函式實現

#include <stdio.h>

int main(void)
{
    int ch;
    FILE *sfp;
    FILE *dfp;
    char sfilename[FILENAME_MAX];
    char dfilename[FILENAME_MAX];
    printf("source filename: "); scanf("%s", sfilename);
    printf("destination filename: "); scanf("%s", dfilename);
    
    
if((sfp = fopen(sfilename, "r")) == NULL) printf("\aSource file open failed.\n"); else { if((dfp = fopen(dfilename, "w")) == NULL) printf("\aDestinatiom file open failed.\n"); else { while((ch = fgetc(sfp)) != EOF) fputc(ch, dfp); fclose(dfp); } fclose(sfp); }
return 0; }

2、二進位制複製、使用fread、fwrite函式實現

#include <stdio.h>

int main(void)
{
    int ch;
    FILE *sfp;
    FILE *dfp;
    char sfilename[FILENAME_MAX];
    char dfilename[FILENAME_MAX];
    printf("Source filename: "); scanf("%s", sfilename);
    printf("Destination filename: "); scanf("%s"
, dfilename); if((sfp = fopen(sfilename, "rb")) == NULL) printf("\aSource file open failed.\n"); else { if((dfp = fopen(dfilename, "wb")) == NULL) printf("\aDestination file open failed.\n"); else { int n; while(n = (fread(&ch, sizeof(int), 1, sfp)) > 0) fwrite(&ch, sizeof(int), 1, dfp); fclose(dfp); } fclose(sfp); } return 0; }