p58 读写文件2
格式化读写文件
- fscanf 和 fprintf
- 也可以对文件进行读写
- 原先的 scanf 和 printf 可以对终端格式化字符串进行读写。
fprintf : 用于打印格式化字符串到指定的文件
fscanf : 用于从指定文件中读取格式化字符串
将当前的日期获取之后,写入到新创建的文件里去。读取并打印到屏幕上。
# include <stdio.h>
# include <stdlib.h>
# include <time.h>
int main(void){
FILE *fp;
struct tm *p;
time_t t; // 声明一个t的变量
// 调用time函数获取时间值到 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;
}
二进制读写文件
- fopen 函数可以指定以文本模式或者二进制模式打开一个文件
- 但这并不意味着,后续对该文件的操作就一定是对应的形式。
# include <stdio.h>
# include <stdlib.h>
int main(void){
FILE *fp;
if((fp = fopen("text.txt","wb")) == NULL)
{
printf("打开文件失败 !\n");
exit(EXIT_FAILURE);
}
// fputc 是往文件流里面写入一个字符
fputc('5',fp);
// 打开是二进制的形式,却往里面写入一个文本
fputc('7',fp);
fputc('6',fp);
fputc('\n',fp);
fclose(fp);
return 0;
}
应该如何使用二进制的形式来读写文件呢?使用 fopen + wb 的模式并不靠谱。
C语言为直接读写文件提供了两个函数,二进制读写文件(fread 和 fwrite)
-
fread 函数用于从指定的文件中读取指定尺寸的数据
# include<stdio.h> size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream); // ptr 读完之后要把数据放到哪去 ptr : 指向存放数据的内存块指针,该内存块的尺寸最小应该是 size * nmemb 个字节 size: 指定要读取的每个元素的尺寸, 最终尺寸等于 size * nmemb nmemb : 指定要读取的元素个数,最终尺寸等于 size * nmemb stream : FILE 对象的指针,指定一个待读取的文件流
-
fwrite 函数:用于将指定尺寸的数据写到指定的文件中
size_t fwrite(const void *ptr,size_t size,size_t nmemb, FILE *stream);
尝试使用 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结构体的指针,从堆里申请空间。
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);
}
strcpy(book_for_write->name, "《票票神之书》");
strcpy(book_for_write->author, "票票");
strcpy(book_for_write->publisher, "票票大学出版社");
book_for_write->date.year = 2022;
book_for_write->date.month = 1;
book_for_write->date.day = 17;
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.mon,book_for_read ->date.day);
fclose(fp);
return 0;
}