1、练习13-1
#include<stdio.h>
int main(void)
{
char s[128];
FILE *fp;
printf("请输入要打开的文件名: ");
scanf("%s", s);
fp = fopen(s, "r");
if (fp == NULL)
printf("该文件不存在。\n");
else
printf("该文件存在。\n");
return 0;
}
2、练习13-2
#include<stdio.h>
int main(void)
{
char s[128];
printf("请输入要打开的文件名: ");
scanf("%s", s);
fopen(s, "w");
return 0;
}
3、练习13-3
#include<stdio.h>
#define NUMBER 6
typedef struct{
char name[100];
double height;
double weight;
}Student;
void swap_Student(Student *x, Student *y)
{
Student temp = *x;
*x = *y;
*y = temp;
}
void sort_by_height(Student *s, int n)
{
int i, j;
for (i = 0; i < n - 1; i++)
{
for (j = n; j > i; j--)
{
if (s[j - 1].height > s[j].height)
swap_Student(&s[j - 1], &s[j]);
}
}
}
int main(void)
{
FILE *fp;
int i;
int ninzu = 0;
double hsum = 0.0;
double wsum = 0.0;
Student std[NUMBER];
if ((fp = fopen("hw.dat", "r")) == NULL)
printf("\a文件打开失败。\n");
else
{
while (fscanf(fp, "%s%lf%lf", std[ninzu].name, &std[ninzu].height, &std[ninzu].weight) == 3)
{
hsum += std[ninzu].height;
wsum += std[ninzu].weight;
ninzu++;
}
sort_by_height(std, NUMBER);
for (i = 0; i < ninzu; i++)
{
printf("%-10s %5.1f %5.1f\n", std[i].name, std[i].height, std[i].weight);
}
printf("---------------------\n");
printf("平均 %5.1f %5.1f\n", hsum / ninzu, wsum / ninzu);
fclose(fp);
}
return 0;
}
4、练习13-4
#include<stdio.h>
int main(void)
{
FILE *fp;
char name[100];
double height, weight;
printf("请输入姓名,身高,体重。\n");
scanf("%s %lf %lf", name, &height, &weight);
if ((fp = fopen("dt_dat", "w")) == NULL)
printf("\a文件打开失败。\n");
else
{
printf("写出姓名,身高,体重。\n");
fprintf(fp, "%s %lf %lf\n", name, height, weight);
fclose(fp);
}
return 0;
}
5、练习13-5
#include<stdio.h>
#include<time.h>
char data_file[] = "datatime.dat";
char temp[128];
void get_data(void)
{
FILE *fp;
if ((fp = fopen(data_file, "r")) == NULL)
{
printf("本程序第一次运行。\n");
printf("当前心情: ");
scanf("%s", temp);
}
else
{
int year, month, day, h, m, s;
fscanf(fp, "%d%d%d%d%d%d", &year, &month, &day, &h, &m, &s);
printf("上一次运行是在%d年%d月%d日%d时%d分%d秒。\n",
year, month, day, h, m, s);
fscanf(fp, "%s", temp);
printf("上一次心情: %s", temp);
printf("当前心情: ");
scanf("%s", temp);
fclose(fp);
}
}
void put_data(void)
{
FILE *fp;
time_t current = time(NULL);
struct tm *timer = localtime(¤t);
if ((fp = fopen(data_file, "w")) == NULL)
printf("\a文件打开失败。\n");
else
{
fprintf(fp, "%d %d %d %d %d %d",
timer->tm_year + 1900, timer->tm_mon + 1, timer->tm_mday,
timer->tm_hour, timer->tm_min, timer->tm_sec);
fprintf(fp, "%s\n", temp);
fclose(fp);
}
}
int main(void)
{
get_data();
put_data();
return 0;
}