利用格式化函数读写文件fprintf、fscanf
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
FILE *fp;
struct tm *p;
time_t t;
time(&t);
p = localtime(&t); //利用时间函数获取今日时间
if ((fp = fopen("date.txt", "w")) == NULL)
{
printf("打开文件失败!\n");
exit(EXIT_FAILURE);
}
fprintf(fp, "%d-%d-%d", 1900 + p->tm_year, 1 + p->tm_mon, p->tm_mday); //格式化写入文件
fclose(fp);
int year, month, day;
if ((fp = fopen("date.txt", "r")) == NULL)
{
printf("打开文件失败!\n");
exit(EXIT_FAILURE);
}
fscanf(fp, "%d-%d-%d", &year, &month, &day); //格式化读取文件
printf("%d-%d-%d\n", year, month, day);
fclose(fp);
return 0;
}
二进制读写文件
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *fp;
if ((fp = fopen("text.txt", "wb