小甲鱼 P58 读写文件2

小甲鱼 P58 读写文件2

格式化读写文件

fscanf()函数:读取

fprintf()函数:写入

将当前的日期读取之后,写入到新创建的文件里面 

#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)//w:不存在创建,存在打开初始化 
	{
		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)//w:不存在创建,存在打开初始化 
	{
		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>
#include <time.h>

int main(void)
{
	FILE *fp;

	if ((fp = fopen("text.txt", "wb")) == NULL)//wb:二进制模式 
	{
		printf("打开文件失败!\n");
		exit(EXIT_FAILURE);
	}

	fputc('5', fp);
	fputc('2', fp);
	fputc('0', fp);
	fputc('\n', fp);
	
	fclose(fp);
	
	return 0; 
}

二进制读写文件爱你

fread()

fwrite()

//证明:打开的形式,和具体写入的模式,没有影响的 
//fread和fwrite将一个结构体写入文件中,然后读取出来,打印屏幕上
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct Date
{
	int year;
	int month;
	int day;
};

struct Book
{
	char name[40];
	char author[40];
	char publisher[40];
	struct Date date;
};

int main(void)
{
	FILE *fp;
	struct Book *book_for_write, *book_for_read;
	
	book_for_write = (struct Book *)malloc(sizeof(struct Book));
	book_for_read = (struct Book *)malloc(sizeof(struct Book));
	if (book_for_write == NULL || book_for_read == NULL)
	{
		printf("内存分配失败!\n");
		exit(EXIT_FAILURE);
	}
	
	strcmp(book_for_write->name, "<带你学C带你飞>");
	strcmp(book_for_write->author, "小甲鱼");
	strcmp(book_for_write->publisher, "清华大学出版社");
	book_for_write->date.year = 2017;
	book_for_write->date.month = 11;
	book_for_write->date.day = 11;
	
	if ((fp = fopen("file.txt", "w")) == NULL)
	{
		printf("打开文件失败!\n");
		exit(EXIT_FAILURE);
	}
	
	fwrite(book_for_write, sizeof(struct Book), 1, fp);
	
	fclose(fp);
	
	
	//为了验证真的是否写入成功,打开,读取,打印 
	if ((fp = fopen("file.txt", "r")) == NULL)
	{
		printf("打开文件失败!\n");
		exit(EXIT_FAILURE);
	}
	
	fread(book_for_read, sizeof(struct Book), 1, fp);
	printf("书名:%s\n", book_for_read->name);
	printf("作者:%s\n", book_for_read->author);
	printf("出版社:%s\n", book_for_read->publisher);
	printf("出版日期: %d-%d-%d\n", book_for_read->date.year, book_for_read->date.month, 
	book_for_read->date.day);
	
	fclose(fp);
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/xiaodingqq/article/details/82985187