格式化读写
代码示例:
void test04()
{
FILE*f_write = fopen("./test4.txt", "w");
if (f_write == NULL)
{
return;
}
fprintf(f_write,"hello world %s","abcd");
fclose(f_write);
FILE*f_read = fopen("./test4.txt", "r");
if (f_read == NULL)
{
return;
}
char temp[1024] = {
0};
while (! feof(f_read))
{
fscanf(f_read,"%s",temp);
printf("%s\n",temp);
}
fclose(f_read);
}
随机位置读写
- fseek(参数1 文件指针 参数2 移动大小 参数3 起始参数 SEEK_SET (从开始)
- SEEK_END 从结尾 SEEK_CUR (从当前位置)
- rewind(文件指针) 将文件光标置首
- error宏 全局变量 perror打印宏的提示错误信息
代码示例:
随机位置读写
void test05()
{
FILE*f_write = fopen("./test5.txt", "wb");
if (f_write == NULL)
{
return;
}
struct Hero heros[] =
{
{
"孙悟空",999},
{
"猪八戒",998},
{
"唐山",997},
{
"傻生",996}
};
for (int i = 0; i < 4; i++)
{
fwrite(&heros[i], sizeof(struct Hero), 1, f_write);
}
fclose(f_write);
FILE*f_read = fopen("./test5.txt", "rb");
if (f_read==NULL)
{
perror("文件加载失败");
return;
}
struct Hero tempHero;
fseek(f_read, -(long)sizeof(struct Hero) * 2, SEEK_END);
rewind(f_read);
fread(&tempHero,sizeof(struct Hero),1,f_read);
printf("姓名:%s,年龄:%d\n",tempHero.name,tempHero.age);
fclose(f_read);
}