我们之前学习的程序,无论是输入数据,还是输出数据,都是对内存的操作。一旦程序结束,数据也就没了。下次打开又得重新输入输出。那么怎么样可以让我们的程序可以实现“记忆”呢?这就需要将程序里面的内容以文件的形式存储到我们的硬盘上,这样子即使断电了,数据仍然在硬盘里面。
申请内存和释放内存。打开文件和关闭文件。fopen和fclose.End Of File.#include<stdio.h>#include<stdlib.h>#include<string.h>void main() { //打开一个文件,或者说跟一个文件建立链接。 //fileopen = fopen(要打开文件,用什么方式打开) FILE * l_fp = fopen("./123.txt", "w");//read 和write模式 char l_arr[] = "我的银行卡是:6222 0205 ...."; char l_temp = 0; if (l_fp == NULL) { printf("文件打开失败。\n"); } else { printf("打开成功。\n"); for (size_t i = 0; i < strlen(l_arr); i++) { putc(l_arr[i],l_fp); }
fclose(l_fp); }
system("pause");}
#include<stdio.h>
#include<stdlib.h>#include<string.h>void main() { FILE *l_p = fopen("./123", "r"); char l_temp = 0; if (l_p == NULL) { printf("无法打开文件"); } else { printf("打开成功\n"); while (l_temp != EOF) { l_temp = getc(l_p); printf("%c", l_temp);
}
fclose(l_p); } system("pause");}getc=getchar 从标准输入里读取下一个字符#include<stdio.h>
#include<stdlib.h>#include<string.h>void main() { FILE*l_p = fopen("./储存", "r"); char l_temp = 0; if (l_p == NULL) { printf("无法打开文件\n"); } else { printf("打开文件成功\n"); l_temp = getc(l_p); printf("%c\n", l_temp); l_temp = getc(l_p); printf("%c\n", l_temp); l_temp = getc(l_p); printf("%c\n", l_temp); } system("pause");}#include<stdio.h>
#include<stdlib.h>#include<string.h>void main() { FILE *l_p = fopen("./123", "r"); char l_temp = 0; if (l_p == NULL) { printf("无法打开文件"); } else { printf("打开成功\n"); while (l_temp != EOF) { l_temp = getc(l_p); printf("%c", l_temp);}
fclose(l_p); } system("pause");}