-
Notifications
You must be signed in to change notification settings - Fork 0
/
test4.c
88 lines (68 loc) · 1.85 KB
/
test4.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
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
#include <stdio.h>
#include <stdlib.h>
#include "array.h"
/* This program will fill an array of structures of size 100 with
* a bunch of names from the file "names.txt".
* It will then write the name to the file "names2.txt", as lastname,
* firstname; then it will remove the last item using "contract",
* and finally report the number of read, write, malloc and free
* calls.
*/
#define CAPACITY 100 // total capacity of the array
struct Name
{
char first[25];
char last[25];
};
void readFile( struct Performance *performance, struct Array *array )
{
FILE *fp;
char buffer[81];
struct Name name;
int retval;
fp = fopen( "names.txt", "r" );
// skip the first line
fgets( buffer, 80, fp );
while (!feof(fp))
{
// this scanf call is unsafe if inputs are wider the first or last strings
retval = fscanf( fp, "%s %s", name.first, name.last );
if (retval==2)
{
writeItem( performance, array, array->nel, &name );
}
}
fclose( fp );
}
int main( int argc, char **argv )
{
struct Name name;
struct Performance *perf;
struct Array *array;
int i;
FILE *fp;
perf = newPerformance();
array = newArray( perf, sizeof( struct Name ), CAPACITY );
readFile( perf, array );
printf( "Read %d records\n", array->nel );
fp = fopen( "names2.txt", "w" );
for (i=0;i<array->nel;i++)
{
readItem( perf, array, i, &name );
fprintf( fp, "%s, %s\n", name.last, name.first );
}
fclose( fp );
contract( perf, array );
printf( "After contraction:\n" );
for (i=0;i<array->nel;i++)
{
readItem( perf, array, i, &name );
printf( "%2d: %s, %s\n", i, name.last, name.first );
}
freeArray( perf, array );
printf( "reads: %5d\n", perf->reads );
printf( "writes: %5d\n", perf->writes );
printf( "mallocs: %5d\n", perf->mallocs );
printf( "frees: %5d\n", perf->frees );
free( perf );
}