Return the current position of a stream
#include <stdio.h> long int ftell( FILE* fp ); off_t ftello( FILE* fp );
libc
The ftell() function returns the current position of the stream specified by fp. This position defines the character that will be read or written by the next I/O operation on the file. The value returned by ftell() can be used in a subsequent call to fseek() to restore the file position to a previous value.
The ftello() function is similar to ftell(), except that the position is returned as an off_t.
The current position of the file or -1L if an error occurred (errno is set).
#include <stdio.h>
#include <stdlib.h>
long filesize( FILE *fp )
{
long int save_pos;
long size_of_file;
/* Save the current position. */
save_pos = ftell( fp );
/* Jump to the end of the file. */
fseek( fp, 0L, SEEK_END );
/* Get the end position. */
size_of_file = ftell( fp );
/* Jump back to the original position. */
fseek( fp, save_pos, SEEK_SET );
return( size_of_file );
}
int main( void )
{
FILE *fp;
fp = fopen( "file", "r" );
if( fp != NULL ) {
printf( "File size=%ld\n", filesize( fp ) );
fclose( fp );
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}
ftell() is ANSI; ftello() is standard Unix
| Safety: | |
|---|---|
| Cancellation point | Yes |
| Interrupt handler | No |
| Signal handler | No |
| Thread | Yes |
errno, fgetpos(), fopen(), fsetpos(), fseek()