-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfiles.cpp
157 lines (105 loc) · 2.02 KB
/
files.cpp
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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
#include<stdio.h>
#include<string.h>
/*********************** Wrinting into Files *********************/
// process 1
int main(){
FILE *fp;
fp=fopen("tet.txt","w");
fprintf(fp,"hdghd");
fprintf(fp,"hdghd\n");
fclose(fp);
return 0;
}
// process 2
int main(){
FILE *fp;
fp=fopen("tet.txt","w");
char str[100];
scanf("%s",str);
fprintf(fp,"%s\n",str);
fprintf(fp,"%s\n",str);
fclose(fp);
return 0;
}
// process 3
int main(){
FILE *fp;
fp=fopen("t5.txt","a"); //clears the file
char str[100];
while(scanf("%s",str)==1){
fputs(str,fp);
fputs("\n",fp);
}
fclose(fp);
return 0;
}
// process 4
int main(){
FILE *fp;
fp=fopen("t5.txt","w"); //clears the file
char str[100];
int num;
while(scanf("%s %d",str,&num)==2){
fprintf(fp,"%s %d",str,num);
}
fclose(fp);
return 0;
}
/*********************** Reading from Files *********************/
// process 1
int main(){
FILE *fp;
fp=fopen("t5.txt","r");
char str[100];
int num;
while(fscanf(fp,"%s %d",str,&num)!=EOF){
//fscanf(fp,"%s",str);
printf("%s %d\n",str,num);
}
fclose(fp);
return 0;
}
// process 2
int main(){
FILE *fp;
fp=fopen("t5.txt","r");
char str[100];
int num;
while(fgets(str,100,fp)){ // takes each line at a time
printf("%s",str);
}
fclose(fp);
return 0;
}
/*********************** Binary Files *********************/
struct threeSome{
int n1,n2,n3;
};
// writing
int main(){
int n;
struct threeSome num;
FILE *fp;
fp=fopen("tnt.bin","wb");
for(n=1;n<5;n++){
num.n1=n;
num.n2=5*n;
num.n3=5*n+1;
fwrite(&num, sizeof(struct threeSome), 1, * fp);
}
fclose(fp);
return 0;
}
// Reading
int main(){
int n;
struct threeSome num;
FILE *fp;
fp=fopen("tnt.bin","rb");
for(n=1;n<5;n++){
fread(&num,sizeof(struct threeSome),1,fp);
printf("n1: %d\nn2: %d\nn3: %d\n",num.n1,num.n2,num.n3);
}
fclose(fp);
return 0;
}