文件:一般指存放在外部介质上数据的集合。
文件名:文件路径+文件名主干+文件后缀 ,如 d:\cc\temp (路径)+file1(文件主干名)+.dat(后缀)
文件分类:ASCII文件 和 二进制文件 ,两中类型的存储方式不同。例如:存放整数 10 000 ;在内存中表示为 0 01 0 0 1 1 1 0 0 0 1 0 0 0 0;以ASCII形式保存 表示为
0 0 1 1 0 0 0 1 0 0 1 1 0 0 0 0 0 0 1 1 0 0 0 0 0 0 1 1 0 0 0 0 0 0 1 1 0 0 0 0 ,每个字符占用一个字节;二进制形式保存表示为:0 0 1 0 0 1 1 1 0 0 0 1 0 0 0 0,表示数字的实际大小。
优缺点:ASCII文件便于对字符进行逐个处理,便于输出字符,但占用存储空间较多,而且要花费时间转换。二进制形式文件,可以减少转换时间,减小存储空间,但不便于对字符进行操作,通常用于保存运算的中间结果。
文件缓冲区:文件缓冲区是一个中转站,用于一次性写入文件或者一次性读出文件。
文件指针:每个被使用的文件都内存中开辟一个相应的文件信息区,用来存放文件的有关信息。
对文件进行读写字符操作代码段:
写入:
#include<cstdio>
#include<cstdlib>
using namespace std;
int main()
{
FILE *f;
char ch;
if((f=fopen("F:\\File.dat","w"))==NULL)//若指定文件不存在,系统会自动建立该文件;w代表write
{
printf("%s","The file can't be opened !");
exit(0);
}
ch=getchar();
ch=getchar();
while(ch!='#')
{
fputc(ch,f);
putchar(ch);
ch=getchar();2
}
fclose(f);
putchar(10);
system("pause");
return 0;
}
读出并写入:
#include<cstdio>
#include<cstdlib>
using namespace std;
int main()
{
FILE *in,*out;
if((in=fopen("F:\\File.dat","r"))==NULL) //打开输入文件
{
printf("%s","The file can't be opened !");
exit(0);
}
if((out=fopen("F:\\File1.dat","w"))==NULL)//打开输出文件
{
printf("%s","The file can't be opened !");
exit(0);
}
while(!feof(in))
fputc(fgetc(in),out); //将从输入文件中读取的字符写入输出文件
fclose(in); //文件的关闭
fclose(out);
system("pause");
return 0;
}