爱星光(istar)高端网站建设,小程序代理多少钱,昆明网站定制,网站加载速度【题目描述】创建一个后缀名为txt的文件#xff0c;并向该文件中写入一个字符串#xff0c;保存起来。再打开该文件#xff0c;读出文件中的内容。 【代码实现】
// 文件的读写
# include stdio.h
# include stdlib.h
# include time.h
int main()…【题目描述】创建一个后缀名为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;
}