8. 结构体与文件 IO
结构体
typedef struct {
char name[20];
int age;
float score;
} Student;
Student s = {"Tom", 20, 89.5};
printf("%s %d\n", s.name, s.age);
文件读写
#include <stdio.h>
int main() {
FILE *fp = fopen("data.txt", "w");
fprintf(fp, "Hello File\n");
fclose(fp);
char buf[100];
fp = fopen("data.txt", "r");
fgets(buf, sizeof(buf), fp);
printf("%s", buf);
fclose(fp);
return 0;
}
fopen 模式:"w" 写、"r" 读、"a" 追加。用完务必 fclose。