文件
文件指针
FILE* pf;//文件指针变量
定义的pf是一个指向FILE类型数据的指针变量,通过文件指针变量能够找到与它关联的文件。
文件的打开和关闭
FILE* fopen(const char* filename, const char* mode);
int fclose(FILE* stream);
文件在读写之前应该先打开文件,在使用结束之后应该关闭文件。
打开方式如下:
“r”(只读) 为了输入数据,打开一个已经存在的文本文件
“w”(只写) 为了输出数据,打开一个文本文件
“a”(追加) 向文本文件尾添加数据
“rb”(只读) 为了输入数据,打开一个二进制文件
“wb”(只写) 为了输出数据,打开一个二进制文件
“ab”(追加) 向一个二进制文件尾添加数据
“r+”(读写) 为了读和写,打开一个文本文件
“w+”(读写) 为了读和写,建议一个新的文件
“a+”(读写) 打开一个文件,在文件尾进行读写
“rb+”(读写) 为了读和写打开一个二进制文件
“wb+”(读写) 为了读和写,新建一个新的二进制文件
“ab+”(读写) 打开一个二进制文件,在文件尾进行读和写
文件的读写
字符输入函数 — fgetc
字符输出函数 — fputc
文本行输入函数 — fgets
文本行输出函数 — fputs
格式化输入函数 — fscanf
格式化输出函数 — fprintf
二进制输入 — fread
二进制输出 — fwrite
文件读写:
#include<stdio.h>
int main()
{
char *a = "helloworld";
FILE* pout = fopen("test.txt", "w");
while (*a != '\0')
{
fputc(*a, pout);
a++;
}
fclose(pout);
FILE* pin = fopen("test.txt", "r");
char ch = fgetc(pin);
while (ch != EOF)
{
printf("%c", ch);
ch = fgetc(pin);
}
fclose(pin);
return 0;
}
二进制读写:
#include<stdio.h>
int main()
{
int a = 1000;
FILE* pout = fopen("test.txt", "w");
fwrite(&a, 4, 1, pout);
fclose(pout);
FILE* pin = fopen("test.txt", "r");
fread(&a, 4, 1, pin);
printf("%d", a);
fclose(pin);
return 0;
}
文件读写函数
fseek
int fseek(FILE* stream, long int offset, int origin);
根据文件指针的位置和偏移量来定位文件指针。
第一个为文件指针,第二个为偏移量,第三个为查询方式。系统给的查询方式有三种,分别为SEEK_SET(将文件指针指向头部,偏移量为跳过前几个字符的数据)、SEEK_CUR(文件指针位置为当前位置,偏移量为跳过几个字符的数据)和SEEK_END(将文件指针指向尾部,偏移量为负值,读取文件尾部数据)。
#include<stdio.h>
int main()
{
FILE* p = fopen("test.txt", "r");
fseek(p, 3, SEEK_SET);
fseek(p, 2, SEEK_CUR);
char ch = fgetc(p);
while (ch != EOF)
{
printf("%c", ch);
ch = fgetc(p);
}
printf("\n");
fseek(p, 0, SEEK_SET);
fseek(p, -5, SEEK_END);
char ch1 = fgetc(p);
while (ch1 != EOF)
{
printf("%c", ch1);
ch1 = fgetc(p);
}
return 0;
}
test.txt文件中的内容为helloworld。改程序输出结果为两个world。
ftell
long int ftell(FILE* stream);
返回文件指针相对于起始位置的偏移量。可以和fseek搭配,计算文件大小。
#include<stdio.h>
int main()
{
FILE* p = fopen("test.txt", "r");
fseek(p, 0, SEEK_END);
long int size = ftell(p);
printf("%d", size);
}
先用fseek函数将文件指针指向文件尾部,然后通过ftell函数计算文件大小。