C语言进阶教程:文件操作高级 - 文件定位 (fseek, ftell, rewind)
在C语言中,对文件进行读写时,系统内部会维护一个文件位置指示器(file position indicator)。这个指示器指向文件中下一次读写操作将要开始的位置。有时,我们需要在文件中自由移动这个位置指示器,而不是仅仅顺序地从头读到尾或从尾部追加。fseek(), ftell(), 和 rewind() 这三个函数就提供了这样的功能。
1. ftell()- 获取当前文件位置指示器
long int ftell(FILE *stream);
- stream: 指向 FILE 对象的指针,该对象指定了流。
ftell() 函数返回指定流的当前文件位置指示器的值。对于二进制文件,这个值是从文件开头算起的字节数。对于文本文件,由于可能存在字符集转换和行尾符转换,这个值的物理意义可能不那么直接,但它仍然可以与 fseek() 配合使用,以返回到之前通过 ftell() 获取的位置。
如果发生错误,ftell() 返回 -1L,并设置全局变量 errno。
示例:
#include <stdio.h>
int main() {
FILE *fp;
long pos;
fp = fopen("example.txt", "w+"); // 以读写方式创建或打开文件
if (fp == NULL) {
perror("Error opening file");
return 1;
}
fprintf(fp, "Hello, World!");
pos = ftell(fp);
if (pos == -1L) {
perror("Error getting file position");
} else {
printf("Current position after writing: %ld\n", pos);
}
fclose(fp);
return 0;
}
2. fseek()- 设置文件位置指示器
int fseek(FILE *stream, long int offset, int whence);
- stream: 指向 FILE 对象的指针,该对象指定了流。
- offset: 相对于 whence 参数指定的起始点的偏移量(以字节为单位)。可以是正数(向文件末尾移动)、负数(向文件开头移动)或零。
- whence: 指定偏移量的起始点。它必须是下列常量之一:
- SEEK_SET: 从文件开头开始计算偏移量。
- SEEK_CUR: 从当前文件位置指示器开始计算偏移量。
- SEEK_END: 从文件末尾开始计算偏移量。(注意:对于二进制文件,从文件末尾偏移通常用于定位到文件末尾之前的某个位置;对于文本文件,其行为可能不可靠或不被所有库支持)。
fseek() 函数成功时返回0。如果发生错误,返回非零值。
重要注意事项:
- 对于二进制文件,fseek() 可以用于定位到文件中的任何字节位置。
- 对于文本文件,offset 必须是0,或者是由 ftell() 返回的值。whence 通常应为 SEEK_SET(当 offset 是 ftell() 返回值时)或 SEEK_SET (当 offset 是0,定位到文件头) 或 SEEK_END (当 offset 是0,定位到文件尾,但后续写入行为可能因模式而异)。在文本模式下使用 fseek 进行任意字节偏移可能导致未定义行为。
- 调用 fseek() 会清除文件流的EOF(end-of-file)指示符,并撤销任何由 ungetc() 函数造成的影响。
- 在读操作和写操作之间切换时,如果文件以更新模式打开(如 "r+", "w+", "a+"),必须在它们之间调用一次文件定位函数(fseek, fsetpos, rewind)或者刷新函数(fflush)。
示例:
#include <stdio.h>
int main() {
FILE *fp;
char buffer[100];
fp = fopen("data.bin", "wb+"); // 二进制读写模式
if (fp == NULL) {
perror("Error opening file");
return 1;
}
// 写入一些数据
fputs("This is some initial data.", fp);
// 移动到文件开头
if (fseek(fp, 0, SEEK_SET) != 0) {
perror("Error seeking to beginning");
fclose(fp);
return 1;
}
printf("Seeked to beginning. Current position: %ld\n", ftell(fp));
// 读取数据
fgets(buffer, sizeof(buffer), fp);
printf("Read from beginning: %s\n", buffer);
// 移动到距离当前位置5个字节处
if (fseek(fp, 5, SEEK_SET) != 0) { // 从文件头偏移5字节
perror("Error seeking to offset 5");
fclose(fp);
return 1;
}
printf("Seeked to offset 5. Current position: %ld\n", ftell(fp));
fgets(buffer, sizeof(buffer), fp);
printf("Read from offset 5: %s\n", buffer);
// 移动到文件末尾 (通常用于获取文件大小或追加前定位)
if (fseek(fp, 0, SEEK_END) != 0) {
perror("Error seeking to end");
fclose(fp);
return 1;
}
long file_size = ftell(fp);
printf("Seeked to end. File size: %ld bytes. Current position: %ld\n", file_size, ftell(fp));
// 从文件末尾向前偏移10个字节 (如果文件足够大)
if (file_size >= 10) {
if (fseek(fp, -10, SEEK_END) != 0) {
perror("Error seeking from end");
}
printf("Seeked to 10 bytes from end. Current position: %ld\n", ftell(fp));
fgets(buffer, sizeof(buffer), fp);
printf("Read from 10 bytes from end: %s\n", buffer);
}
fclose(fp);
return 0;
}
3. rewind()- 将文件位置指示器重置到文件开头
void rewind(FILE *stream);
- stream: 指向 FILE 对象的指针,该对象指定了流。
rewind() 函数将指定流的文件位置指示器设置到文件的开头。它等效于 (void)fseek(stream, 0L, SEEK_SET),但 rewind() 还会清除流的错误指示符(通过 clearerr(stream))。
示例:
#include <stdio.h>
int main() {
FILE *fp;
char ch;
fp = fopen("example.txt", "w+");
if (fp == NULL) {
perror("Error opening file");
return 1;
}
fputs("Line 1\nLine 2", fp);
printf("After writing, position: %ld\n", ftell(fp));
rewind(fp); // 回到文件开头
printf("After rewind, position: %ld\n", ftell(fp));
printf("Contents after rewind:\n");
while ((ch = fgetc(fp)) != EOF) {
putchar(ch);
}
// 检查错误指示符是否被清除 (rewind会清除)
if (ferror(fp)) {
printf("\nError indicator is set! (This shouldn't happen after rewind unless new error)\n");
} else {
printf("\nError indicator is clear.\n");
}
fclose(fp);
return 0;
}
4. 应用场景
- 随机访问文件:直接跳转到文件中的特定记录或数据块进行读写,而不是顺序处理整个文件。这对于数据库文件或大型数据文件非常有用。
- 获取文件大小:通过 fseek(fp, 0, SEEK_END) 将位置指示器移到文件末尾,然后用 ftell(fp) 获取文件大小(主要用于二进制文件)。
- 重复读取文件内容:使用 rewind() 或 fseek(fp, 0, SEEK_SET) 可以方便地重新从文件头开始读取。
- 修改文件中的特定部分:定位到需要修改的位置,然后写入新数据。
总结
fseek(), ftell(), 和 rewind() 是C语言中进行文件定位的关键函数。它们使得程序能够灵活地控制文件读写的位置,从而实现对文件的随机访问和更复杂的文件操作。在二进制模式下,这些函数基于字节偏移工作,非常直观。在文本模式下,由于潜在的字符集和行尾转换,使用时需要更加小心,通常 offset 应为0或 ftell() 的返回值。