文件的操作
老规矩笔记自取~:文件操作进阶笔记
❤️欢迎喜欢学习C/C++的朋友互关一起努力!!❤️
一、文件的随机读写
1. fseek 定位文件指针函数
根据文件指针的位置和偏移量来定位文件指针
改变原文件指针指向的位置
int fseek( FILE *stream, long offset, int origin );
参数:文件地址,偏移量,起始位置
这里的起始位置
分为
SEEK_CUR 当前位置
Current position of file pointer
SEEK_END 文件字符的末位(最后一个字符的下个位置)
End of file
SEEK_SET 文件起始位置(第一个字符的起始位)
Beginning of file
偏移量右正左负
返回值:成功返回,0
用一段代码感受:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
int main()
{
//FILE* fp = fopen("C:\\Users\\yujing wang\\Desktop\\test.txt", "w");//写入
FILE* fp = fopen("C:\\Users\\yujing wang\\Desktop\\test.txt", "r");//读取
if (fp == NULL)
{
perror("fopen");
return -1;
}
//fputs("abcde", fp);//写入abc
fseek(fp, 1, SEEK_SET);//第二个字符
printf("%c", fgetc(fp));
fseek(fp, 0, SEEK_CUR);//与上面一样
printf("%c", fgetc(fp));
fseek(fp, -1, SEEK_END);//最后一个字符
printf("%c", fgetc(fp));
fclose(fp);
fp = NULL;
return 0;
}
运行结果和想象的一样
2. ftell 当前偏移量函数
返回文件指针相对于起始位置的偏移量
方便我们知道现在文件指针指向哪个位置
long int ftell ( FILE * stream );
参数:文件地址
返回值:偏移量
还是一段代码搞起~
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE* fp = fopen("C:\\Users\\yujing wang\\Desktop\\test.txt", "r");//读取
if (fp == NULL)
{
perror("fopen");
return -1;
}
fseek(fp, 1, SEEK_SET);//指向第二个字符
printf("%ld", ftell(fp));
fclose(fp);
fp = NULL;
return 0;
}
结果符合我们的猜想
3. rewind 返回起始位置函数
让文件指针的位置回到文件的起始位置
void rewind ( FILE * stream );
参数:文件地址
返回值:NULL
把刚才的代码再加一行
int main()
{
FILE* fp = fopen("C:\\Users\\yujing wang\\Desktop\\test.txt", "r");//读取
if (fp == NULL)
{
perror("fopen");
return -1;
}
fseek(fp, 1, SEEK_SET);//指向第二个字符
rewind(fp);
printf("%ld", ftell(fp));
fclose(fp);
fp = NULL;
return 0;
}
运行结果
偏移量变为0了
二、文本文件和二进制文件
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)