forked from portfoliocourses/c-example-code
-
Notifications
You must be signed in to change notification settings - Fork 0
/
copy_file.c
48 lines (41 loc) · 1.22 KB
/
copy_file.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/*******************************************************************************
*
* Program: File Copy demonstration
*
* Description: Example of how to copy a file with C.
*
* YouTube Lesson: https://www.youtube.com/watch?v=ceODxfZWZIo
*
* Author: Kevin Browne @ https://portfoliocourses.com
*
*******************************************************************************/
#include <stdio.h>
// program should be provided with two command line arguments, the name of the
// file and the name of the copy, e.g. copy_file file.txt copy.txt
int main(int argc, char *argv[])
{
FILE *file, *copy;
// make sure the correct number of arguments are provided
if (argc != 3)
{
printf("Argument number error.\n");
return 1;
}
// open the file for reading, and the copy for writing
file = fopen(argv[1], "r");
copy = fopen(argv[2], "w");
// exit if the file(s) could not be opened
if (file == NULL || copy == NULL)
{
printf("Error opening file(s).\n");
return 1;
}
// copy the content from the file to the copy one character at a time
char c;
while ( (c = fgetc(file)) != EOF )
fputc(c, copy);
// close the files when we are done with them
fclose(file);
fclose(copy);
return 0;
}