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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
| #include "stdafx.h"
#include <stdio.h>
#include <conio.h>
#include <io.h>
#include <fcntl.h>
#include <sys\stat.h>
int main()
{
int handle1, handle2,[COLOR="DarkOrchid"] nrd, nwr, trd=0, twr=0,[/COLOR] fsize;
char msg[1024]="";
// 1st way
if ( (handle1 = open("D:\\FILES.TXT", O_RDONLY | O_TEXT)) == -1)
{
perror ("Error with 1st Source file:");
return 1;
}
else
{
if ((handle2 = open("D:\\COPY1.TXT", O_CREAT | O_WRONLY | O_TEXT, S_IREAD | S_IWRITE )) == -1)
{
perror ("Error with 1st Destination file:");
return 2;
}
else
{
while ((nrd = read(handle1, msg, 1024))!=0)
{
[COLOR="red"] nwr = write(handle2, msg, nrd);
trd+=nrd;
twr+=nwr;[/COLOR]
}
[COLOR="rgb(153, 50, 204)"]fsize = lseek[/COLOR](handle1, 0L, SEEK_END);
close (handle1);
close (handle2);
printf ("\n1)Copying the file by blocks of 1024 bytes with OPEN function\n");
printf ("Totally read: \t\t%10d bytes\n Totally written: \t\t%10d bytes\n File size is : \t\t%10d bytes\n\n", trd, twr, fsize);
}
}
// 2 way
FILE *f_in, *f_out;
char *name1="D:\\FILES.TXT", *name2="D:\\COPY2.TXT", [COLOR="rgb(153, 50, 204)"]ch;[/COLOR]
if ( (f_in=fopen(name1, "rb") )==NULL)
{
perror ("Error with 1st Source file:");
return 3;
}
else
{
if((f_out=fopen(name2, "wb"))==NULL)
{ perror("Error with 2st Destination file:");
return 4;
}
else
{ fsize=0;
do
{
[COLOR="rgb(153, 50, 204)"] ch=fgetc(f_in);
if (ch != EOF)
{
fputc(ch, f_out);
fsize++;
}
}
while[COLOR="red"] (!feof(f_in));
fclose(f_out);[/COLOR]
printf ("\n2) Copying the file by 1 char with FOPEN function\n");
printf("Totally read:\t\t%10d bytes\n\n", fsize);
}
}
// 3 way
name2="D:\\COPY3.TXT";
if ((f_out=fopen(name2, "[COLOR="rgb(153, 50, 204)"]wb[/COLOR]"))==NULL)
{ perror("Error with 3st Destination file:");
return 5;
}
else
{[COLOR="rgb(153, 50, 204)"]
fsize=0;
fseek(f_in, 0L, SEEK_SET);
while (!feof(f_in))
{
if (fgets(msg, 1024, f_in)!=NULL)
{
fputs(msg, f_out);
fsize++;[/COLOR]
}
}
fclose(f_in);
fclose(f_out);
printf ("\n2) Copying the file by 1 string with FOPEN function\n");
printf("Totally read:\t\t%10d line \n\n", fsize);
}
printf ("\n3)Reading numbers for Array elements:\n");
name1="D:\\MAS.TXT";
int a[10], i=0;
[COLOR="rgb(153, 50, 204)"]if ((f_in=fopen(name1, "r"))==NULL)[/COLOR]
{
perror ("Error with 2nd Source file: ");
return 6;
}
else
{
while (!feof(f_in)&& (i<10))
{
fscanf(f_in, "%d", &a[i]);
printf("a[%d]=%d\n", i, a[i++]);
}
fclose(f_in);
}
getch ();
return 0;
} |