c语言文件是一种流式文件,总是按照数据写入文件的顺序存放的,因此将文件看成是有一个一个字符(字节)数据顺序组成的序列;
文件的读取改写是通过指针来进行访问的;
文件指针是指指向文件的指针变量,一个文件指针指向某个文件是指针指向了该文件内存缓冲区的首地址。通过文件指针对其所指向的文件进行操作; 定义文件指针的一般格式为:
FILE * 指针变量名
文件的打开与关闭
#include<stdio.h>
#include<stdlib.b>
{
int main()
{
FILE *file; //定义文件指针变量名
file = fopen("文件名","r"); //通过文件指针访问文件打开函数fopen, 参数1 : 文件名; 参数2:打开方式
if(file == NULL) //判断是否成功的打开了文件
{
printf("不能打开文件\n");
}
else
{
printf("已经打开文件\n")
}
}
return;
}
上面表格是打开的方式; 通常文件的打开会用 逻辑运算符 |
FILE *file;
file = fopen("s.txt","w");
fputc('A',file); //写文件字符函数
fclose(file);
int fputc (int c, File *file) file为文件指针,他的值是执行fopen()打开文件是获得的; n为输出的字符量
完整的文件打开,输入,关闭
#include <stdio.h>
#include<stdlib.h>
void main()
{
int ch, i;
FILE *file; //文件指针变量
if((file = fopen("b.txt","w")) == NULL)//判断是否成功打开
{
printf("can't open\n");
exit(0); //关闭文件
}
for( i = 0 ; i< 9; i++) //输出9个字符
{
ch=fputc(i+33,file); // fputc()将字符写到文件子针所指向的文件里面
if(ch ==EOF) //是否写入失败
{
printf("can't write\n");
exit(0);
}
}
fclose(file);
file = fopen("b.txt","r");
while((ch =fgetc(file))!= EOF)
{
fputc(ch,stdout);
putchar('\t');
}
putchar('\n');//该函数将制定的表达式的值所对应的字符输入到标准输出终端上。 每次只能输出一个字符
fclose(file); //关闭文件
}
exit(0) 关闭文件
int fputc(int c, FILE *file) 将字符c写到文件指针file所指向文件的当前写指针的位置;
int getchar(void); 从stdio流中读字符
getc()和fgetc() , putc()和fputc() 功能相同;
文件字符串打印
#include<stdio.h>
#include<stdlib.h>
char s[5][6] ={"I","love","you","of","world"};
void main()
{
char a[200];
int i;
FILE *file,*file1;
file = fopen("123.txt","w");
if(file == NULL)
{
printf("can't open file\n");
exit(0);
}
for(i =0; i< 5; i++)
fputs(s[i],file);
fclose(file);
file = fopen("123.txt","r");
if((file1=fopen("1234.txt","w"))==NULL)
{
printf("can't open 1234.txt.\n");
exit(0);
}
while(fgets(a,200,file)!= NULL) //读取file文件并储存
{
fputs(a,file1); //想指定的文件写入字符串
fputs(a,stdout); //
}
putchar('\n'); //想终端输出
fclose(file);
fclose(file1);
}
char fgets(char *buf,int bufsize, FILE stream) 参数:*buf:字符型指针,指向用来存储所得数据的地址。 bufsize:整形数据,值明存储数据的大小。 *stream:文件结构体指针,将要读取的文件流。
小结: FILE *指针变量
指针变量 = fopen(“文件名字”,“读取方式”)
if(指针变量 ==NULL){printf(“…..”); exit(0)}
通过复制,读取文件内容;