C语言文件访问分为顺序文件访问和随机文件访问。
关于文件位置指示符:
rewind():把文件位置指示符设置至文件开头,函数原型如下:
void rewind(FILE *stream);
rewind()函数只有一个参数stream:
rewind()函数的返回值为空void。
在不关闭文件的情况下,调用rewind()函数后,文件的位置指示符被设置到文件的开头0字节处;此时,可以从文件开头处开始,重新读取文件数据。
ftell():获取文件位置指示符的当前位置,函数原型如下:
long int ftell(FILE *stream);
ftell()函数只有一个参数stream:
ftell()函数返回值类型为long型:
fseek():设置文件位置指示符的位置,函数原型如下:
int fseek(FILE *stream, long offset, int origin);
fseek()函数有三个参数:
origin有三种取值,如下图所示:
fseek()函数的返回值为int型:
C语言标准描述如下:
1. If successful, fseek returns 0.
2. Otherwise, it returns a nonzero value.
验证rewind函数是否将文件位置指示符设置至文件开头,示例代码如下所示:
#define BUFLEN 6
int main()
{
//
char msg[] = "abcdefghijklmnopqrstuvwxyz";
FILE* fp;
char buf[BUFLEN] = { 0 };
//
if ((fp = fopen("1.txt", "w")) == NULL)
{
printf("Failed to open file.\n");
exit(1);
}
//
if ((fputs(msg, fp)) == EOF)
{
printf("Failed to write file.\n");
exit(1);
}
//
fclose(fp);
//
if ((fp = fopen("1.txt", "r")) == NULL)
{
printf("Failed to open file.\n");
exit(1);
}
printf("After open file, position = %ld\n", ftell(fp));
//
fgets(buf, BUFLEN, fp);
printf("After read sting %s, position = %ld\n", buf, ftell(fp));
//
fgets(buf, BUFLEN, fp);
printf("After read sting %s, position = %ld\n", buf, ftell(fp));
//
rewind(fp);
printf("After rewind, position = %ld\n", ftell(fp));
//
fgets(buf, BUFLEN, fp);
printf("After read sting %s, position = %ld\n", buf, ftell(fp));
//
fclose(fp);
return 0;
}
代码运行结果如下图所示:
使用fseek()函数设置文件位置指示符,示例代码如下所示:
#define MAX 50
int main()
{
//变量定义
FILE* fp;
int data = 0;
int count = 0;
int arr[MAX] = { 0 };
long offset;
//初始化数组
for (count = 0; count < MAX; count++)
{
arr[count] = count * 10;
}
//打开文件
if ((fp = fopen("1.dat", "wb")) == NULL)
{
printf("Failed to open file.\n");
exit(1);
}
//写文件
if ((fwrite(arr, sizeof(int), MAX, fp)) != MAX)
{
printf("Failed to write file.\n");
exit(1);
}
//关闭文件
fclose(fp);
//打开文件
if ((fp = fopen("1.dat", "rb")) == NULL)
{
printf("Failed to open file.\n");
exit(1);
}
//读文件
while (1)
{
//
printf("请输入数组元素的下标:>\n");
scanf("%ld", &offset);
//
if (offset < 0)
{
break;
}
else if(offset > MAX - 1)
{
continue;
}
//
if ((fseek(fp,(offset*sizeof(int)),SEEK_SET)) != 0)
{
printf("Failed to use fseek().\n");
exit(1);
}
//
fread(&data, sizeof(int), 1, fp);
//
printf("arr[%ld] = %d\n", offset, data);
}
//关闭文件
fclose(fp);
return 0;
}
代码运行结果如下图所示: