C 编程中fseek、ftell的用法总结

fseek 函数功能是将文件指针移动到指定的地方,因此可以通过fseek重置文件指针的位置。函数原型:

int  fseek(FILE *stream, long offset,  int origin);

参数说明:

stream : 待移动的FILE型指针变量

offset:偏移量,每次移动多少个字节

origin: 指针开始的位置

返回值: 如果fseek ()返回值为0,表示执行成功,如果返回值为非0, 则执行失败。

尽管随着读取文件的进行,origin和文件指针的位置都会随着发生变化,但是在调fseek()函数时,给它传入的origin参数只能是以下三种之一:

SEEK_CUR : 文件指针目前的位置

SEEK_END : 文件末尾处

SEEK_SET : 文件开始处

当文件以附加文档形式打开时,当前的文件指针位置是指在上次进行I/O操作之后的文件指针位置上。并不是这次要准备追加文本的目标位置处。如果以附加文档形式打开一个文件时,这个文件此前没有进行过I/O操作,那么此时的文件指针指在文件的开始位置处。对于以文本模式打开的流,限制使用fseek函数,因为回车换行符与单行换行符之间的转换会导致fseek产生意外的结果。fseek只有在下面两种情况下才能保证当文件以文档模式打开时能正确使用fseek函数:

1.Seeking with an offset of 0 relative to any of the origin values. (与起始位置相对偏移为0的重置,即没有改动指针位置)

2.Seeking from the beginning of the file with an offset value returned from a call to ftell.(origin设置为 SEEK_SET ,offset为调用ftell返回的值时进行的指针位置重置情况)

下面透过一个案例来进一步说明fseek的用法:

/* FSEEK.C: This program opens the file FSEEK.OUT and
 * moves the pointer to the file's beginning.
 */
 
#include <stdio.h>
 
void main( void )
{
   FILE *stream;
   char line[81];
   int  result;
 
   stream = fopen( "fseek.out", "w+" );
   if( stream == NULL )
      printf( "The file fseek.out was not opened
" );
   else
   {
      fprintf( stream, "The fseek begins here: "
                       "This is the file 'fseek.out'.
" );
      result = fseek( stream, 23L, SEEK_SET);
      if( result )
         printf( "Fseek failed" );
      else
      {
         printf( "File pointer is set to middle of first line.
" );
         fgets( line, 80, stream );
         printf( "%s", line );
 
      }
      fclose( stream );
   }
}
 刚好"The fseek begins here: " 包括空格在内为23个字符,所以下次输出从24个字符位置开始:

Output

File pointer is set to middle of first line.

This is the file 'fseek.out'.

 

ftell 函数获取一个文件指针的当前位置,函数原型:

long     ftell(FILE *stream);

参数说明:stream : 目标参数的文件指针

ftell 函数目标文件指针的当前位置,如果流是以文本模式打开的, 那么ftell的返回值可能不是文件指针在文件中距离开始文件开始位置的物理字节偏移量,因为文本模式将会有换行符转换。如果ftell函数执行失败,则会返回-1L。

案例说明:

/* FTELL.C: This program opens a file named FTELL.C
 * for reading and tries to read 100 characters. It
 * then uses ftell to determine the position of the
 * file pointer and displays this position.
 */
 
#include <stdio.h>
 
FILE *stream;
 
void main( void )
{
   long position;
   char list[100];
   if( (stream = fopen( "ftell.c", "rb" )) != NULL )
   {
      /* Move the pointer by reading data: */
      fread( list, sizeof( char ), 100, stream );
      /* Get position after read: */
      position = ftell( stream );
      printf( "Position after trying to read 100 bytes: %ld
",
              position );
      fclose( stream );
   }
}
上面的文件首先通过
fread(list,sizeof(char),100,stream) 每次读取一个char大小的字符,重复读取100次,因为一个char的大小为1, 所以执行完 fread()这个语句, 此时的stream指针的位置是stream中的位置100处,然后通过ftell(stream)去提取stream流中当前文件指针的位置,那么返回的肯定就是100了,因为它通过fread()函数已经从文件的起始处移动到了100 这个位置了。
 

Output

Position after trying to read 100 bytes: 100

 

原文地址:https://www.cnblogs.com/AI-Algorithms/p/3391346.html