一个简单的文件操作程序
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *fp;
if ((fp = fopen("text.txt", "w")) == NULL) // fopen() 打开文件并判断是否打开成功
{
printf("File open error\n");
exit(0);
}
fprintf(fp, "Hello World"); // fprintf() 向文件中写入信息
if (fclose(fp)) // fclose() 关闭文件并判断是否关闭成功
{
printf("File close error\n");
exit(0);
}
return 0;
}
代码说明
每个文件都有文件名称、文件状态、文件位置等信息,因此 C 语言定义了
FILE
结构类型来保存这些信息。如下为定义一个文件指针fp
,指向该文件对应的结构变量,即可通过文件指针访问该文件。FILE *fp;
fp = fopen("demo.txt", "w");
fopen()
函数用来打开一个文件,其调用的一般形式如下,其中“使用文件方式”如表所示。文件顺利打开后,指向文件的指针就会被返回;如果文件打开失败,则返回 NULL,因此一般使用上例中的方式进行判断。文件指针名 = fopen(文件名, 使用文件方式);
常用的文件打开方式参数表
含义 | 文本文件 | 二进制文件 |
---|---|---|
只读文件 | r | rb |
只写文件 | w | wb |
增加文件 | a | ab |
可读可写 | w+ | wb+ |
fclose()
函数用来关闭一个文件,文件关闭成功后,函数返回 0,否则返回非零值。一旦明确程序不再访问一个文件之后,需要立即显示关闭该文件,以释放文件占用的资源。
文件操作函数
输入输出重定向函数
C 标准函数库提供了输入/输出重定向函数 freopen()
,将标准输入/输出指向文件,这样在使用 scanf()
输入和 printf()
输出时直接访问文件。
freopen(文件名, 使用文件方式, stdin); // 输入重定向
freopen(文件名, 使用文件方式, stdout); // 输出重定向
#include <stdio.h>
#include <stdlib.h>
/**
* 输入/输出重定向
*/
int main(void)
{
FILE *fp;
char str1[15], str2[15];
freopen("text.txt", "r", stdin);
freopen("demo.txt", "w", stdout);
while(scanf("%s %s", &str1, &str2) != EOF)
printf("将读取到的字符串写入文件:%s %s", str1, str2);
fclose(stdin); // 关闭输入流
fclose(stdout); // 关闭输出流
return 0;
}
格式化文件读写函数
一般调用形式如下:
fscanf(文件指针, 格式字符串, 输入表);
fprintf(文件指针, 格式字符串, 输入表);
数据块读写函数
fread()
和 fwrite()
函数,可以实现对数据的整体读写,被读写的数据可以是一个结构体或数组,也可以是一个简单数据,但要求文件中每一组数据的存储长度相同。如果函数调用成功,返回值为数据个数,否则返回值为 0。一般调用形式如下:
fread(数据区首地址, 每次读取的字节数, 读取次数, 文件指针);
fwrite(数据区首地址, 每次写入的字节数, 写入次数, 文件指针);
文件读写示例
下例定义了一个结构体,存入文件中,再从文件中读入。
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
char name[15];
int age;
}Stu;
int main(void)
{
Stu stu, temp;
FILE *fp;
printf("输入学生姓名:");
scanf("%s", &stu.name);
printf("输入学生年龄:");
scanf("%d", &stu.age);
if ((fp = fopen("demo.txt", "w")) == NULL)
{
exit(0);
}
fwrite(&stu, sizeof(Stu), 1, fp);
fclose(fp);
if ((fp = fopen("demo.txt", "r")) == NULL)
{
exit(0);
}
fread(&temp, sizeof(Stu), 1, fp);
printf("姓名:%s,年龄:%d\n", temp.name, temp.age);
fclose(fp);
return 0;
}
简单的文件读取/保存函数:
/**
* 读取文件
*/
void load(Stu stu[], int *nPtr)
{
FILE *fp;
int i;
if ((fp = fopen("demo.txt", "r")) == NULL)
{
*nPtr = 0;
return;
}
for (i = 0; fread(&stu[i], sizeof(Stu), 1, fp) != 0; ++i)
*nPtr = i;
fclose(fp);
}
/**
* 保存到文件
*/
void save(Stu stu[], int n)
{
FILE *fp;
if ((fp = fopen("demo.txt", "w")) == NULL)
{
printf("保存到文件失败\n");
exit(0);
}
fwrite(stu, n * sizeof(Stu), 1, fp);
fclose(fp);
}