【题目描述】创建一个后缀名为txt的文件,并向该文件中写入一个字符串,保存起来。再打开该文件,读出文件中的内容。
【代码实现】
// 文件的读写
# include <stdio.h>
# include <stdlib.h>
# include <time.h>
int main()
{
FILE * fp = fopen("20231202dream_aleaf.txt", "w");
if (fp == NULL) {
exit(0); // 出错了,要退出程序
}
time_t t;//将t声明为时间变量
struct tm * p;//struct tm是一个结构体,声明一个结构体指针
time(& t);
p = localtime(& t);//获得当地的时间
fprintf(fp, "Now time is %d-%d-%d %d:%d:%d\n", 1900 + p->tm_year, 1 + p->tm_mon, p->tm_mday, p->tm_hour, p->tm_min, p->tm_sec);
fprintf(fp, "Please strive for it!\n");
fprintf(fp, "人生自古谁无死,留取丹心照汗青!\n");
fprintf(fp, "纸上得来终觉浅,绝知此事要躬行!\n");
fprintf(fp, "春眠不觉晓,处处闻啼鸟!\n夜来风雨声,花落知多少!");
fclose(fp); // 关闭文件
char ch;
fp = fopen("20231202dream_aleaf.txt", "r");
while ( (ch = fgetc(fp)) != EOF) {
putchar(ch);
}
fclose(fp); // 关闭文件
return 0;
}
【书上参考答案】
# include "stdio.h"
# include "string.h"
# include <conio.h>
int main()
{
FILE * fp; // fp是一个FILE类型的变量,用它来保存一个文件的指针。
char pathName[200], txt1[20] = {'\0'}, txt2[20] = {'\0'};
int fileLen;
// 打开文件
printf("Please type the path name of the file\n");
scanf("%s", pathName); // 输入文件的指定路径,pathName是一个字符型的数组首地址,用来保存文件的路径
// 盘符信息要以“C:\\”的形式输入,整个路径名中不能出现空格符。比如C:\\Users\\dream\\Downloads\\test.txt
// FILE * fopen(char * filename, char * type); // 打开指定路径的文件
fp = fopen(pathName, "w"); // 打开文件,如果磁盘上不存在该文件,则系统会自动生成一个同样名称的空文件。参数w是指以写方式打开一个文本文件
// 将字符串写入文件
printf("Please input a string to this file\n");
scanf("%s", txt1); // 输入要存储的内容,txt1是字符型的数组首地址,用来保存输入的字符串
fileLen = strlen(txt1); // 计算字符串长度
// int fwrite(void * buf, int size, int count, FILE * fp); // 写文件函数
fwrite(txt1, fileLen, 1, fp); // 写入文件
// int fclose(FILE * fp); // 关闭文件
fclose(fp); // 关闭文件
printf("The file has been saved\n");
printf("The content of the file: %s is\n", pathName);
fp = fopen(pathName, "r"); // 打开文件,参数r是指以读方式打开一个文本文件
if (fp == NULL) {
printf("Error!\n");
}
// int fread(void * buf, int size, int count, FILE * fp); // 读文件函数
fread(txt2, fileLen, 1, fp); // txt2是字符型的数组首地址,用来保存从文件中读出的字符串
printf("%s\n", txt2);
getche(); // 输入后立即从控制台取字符,不以回车为结束,且立刻显示在屏幕上(带回显)。
return 0;
}