-
Notifications
You must be signed in to change notification settings - Fork 0
/
cfileop.c
93 lines (79 loc) · 2 KB
/
cfileop.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
88
89
90
91
92
93
#include <stdio.h>
#include <string.h>
#define MAX 50
struct person {
char *name;
int code;
int number;
};
int createBinFile(char *fname) {
FILE *fp;
struct person newrecord;
// Open for binary writing
fp = fopen(fname,"w");
if (!fp) {
printf("Unable to open file!");
return -1;
}
// Just write three records, so we have
// something to play with. Normally you would
// do this with a loop and/or user input!
newrecord.name="aaa bbbb";
newrecord.code=12345;
newrecord.number=1;
fwrite(&newrecord, sizeof(struct person), 1, fp);
newrecord.name="cc ddd";
newrecord.code=1234578;
newrecord.number=2;
fwrite(&newrecord, sizeof(struct person), 1, fp);
newrecord.name="eeee ffffff";
newrecord.code=123456;
newrecord.number=3;
fwrite(&newrecord, sizeof(struct person), 1, fp);
fclose(fp);
return 0;
}
int readBinFile(char *fname) {
FILE *fp;
struct person myrecord;
fp=fopen(fname,"r");
if (!fp) {
printf("Unable to open file!");
return -1;
}
printf("The following records are in the binary file %s:\n", fname);
while (fread(&myrecord,sizeof(struct person),1,fp) != NULL) {
printf("%s\n", myrecord.name);
printf("%d\n", myrecord.code);
printf("%d\n\n", myrecord.number);
}
fclose(fp);
return 0;
}
void delete_record(char* filename, char* record_name){
FILE* fptr;
FILE* fptr2;
fptr = fopen(filename, "r");
fptr2 = fopen("temp.txt", "w+");
struct person myrecord;
while(fread(&myrecord, sizeof(struct person), 1, fptr) != NULL){
if(strcmp(record_name, myrecord.name) == 0){
printf("Record found and deleted.\n");
}
else{
fwrite(&myrecord, sizeof(struct person), 1, fptr2);
}
}
fclose(fptr);
fclose(fptr2);
remove(filename);
rename("temp.txt", filename);
}
void main(int argc, char *argv[]){
char* filename = argv[1];
createBinFile(filename);
readBinFile(filename);
char* record_name = "kkk cccc";
delete_record(filename, record_name);
readBinFile(filename);
}