-
Notifications
You must be signed in to change notification settings - Fork 0
/
savestruct2file.c
42 lines (31 loc) · 967 Bytes
/
savestruct2file.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
#include <stdio.h>
typedef struct
{
char name[50];
int score;
} Student;
int main(void)
{
Student s;
int i; // a counter
FILE *fp;
fp = fopen("myfile.txt","w");
for ( i = 1; i <= 5; i++ ) // input 5 records
{
// input student name
printf("Name: ");
scanf("%s", s.name); // fgets() better to use but scanf() simpler; see ref.
// input score
printf("Score: ");
scanf("%d", &s.score); // note the ampersand with scanf() in case of non-string data
// save record to file
fprintf(fp,"%s,%d\n",s.name,s.score);
printf("Record: %s,%d saved \n", s.name, s.score);
}
fclose(fp);
printf("%d record(s) saved\n",i-1);
return 0;
}
// ref:
// http://www.cprogramming.com/tutorial/c/lesson3.html
// http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1044652485&id=1043284385