Skip to content

Instantly share code, notes, and snippets.

@EvanWieland
Created September 7, 2022 00:23
Show Gist options
  • Save EvanWieland/1d630c5a9032a7621c0a2768f66b8d35 to your computer and use it in GitHub Desktop.
Save EvanWieland/1d630c5a9032a7621c0a2768f66b8d35 to your computer and use it in GitHub Desktop.
This program copies a file from one location to another.
//
// FileCopy.c
//
// This program copies a file from one location to another.
//
// Evan Wieland
// 9/6/2022
//
#include <stdio.h>
#include <sys/stat.h>
#define PATH 128
#define BLOCK 256
// Copy contents from one file to another
int cp(char *source, char *dest)
{
FILE *fpSource, *fpDest;
char buf[BLOCK];
size_t size;
if ((fpSource = fopen(source, "rb")) == NULL) {
fprintf(stderr, "Error: Can't open %s", source);
return 3;
}else if ((fpDest = fopen(dest, "w")) == NULL) {
fprintf(stderr, "Error: Can't open %s", dest);
return 4;
}
while ((size = fread(buf, 1, BLOCK, fpSource)) > 0) {
fwrite(buf, 1, size, fpDest);
}
printf("Copied %s to %s\n", source, dest);
fclose(fpSource);
fclose(fpDest);
return 0;
}
int main() {
struct stat st;
// Get source file from user
char source[128];
printf("Source file: ");
scanf("%s", source);
// Check if source file exists
if (stat(source, &st) == -1) {
fprintf(stderr, "Error: %s does not exist\n", source);
return 1;
}
// Get dest file from user
char dest[128];
printf("Destination file: ");
scanf("%s", dest);
// Check if dest file exists
if (stat(dest, &st) == 0) {
fprintf(stderr, "Error: %s already exists\n", dest);
return 2;
}
return cp(source, dest);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment