Requirement: when reading a file, you need to know the total number of characters in the file, which may be to define the buffer size or copy the file in advance. It can also be used to dynamically create arrays.
Before proceeding to these two questions, let's take a look at the two functions. These two functions can work together to realize the function of calculating the size.
Function 1: fseek
Library functions in stdio:
Function prototype: int fseek (FILE * stream, long int offset, int whence );
Function: sets the position of the file pointer.
Parameters:
Stream: The file stream to be read.
Whence: the position of the file source pointer. The value can be one of the three: SEEK_SET, SEEK_CUR, and SEEK_END, indicating the start position, current position, and end position of the file respectively.
Offset: the size of the offset Based on whence.
Therefore, the overall function of this function is to move the file pointer from any location, such as the most commonly used SEEK_SET, SEEK_CUR, SEEK_END, and offset. After the function is executed, the file pointer is moved to the whence + offset position.
Return Value: 0 is returned for successful execution, and non-zero is returned for failed execution.
Function 2: ftell
Library functions in stdio:
Function prototype: long int ftell (FILE * stream );
Function: read/write location of the current file.
Returned value: the number of bytes that the current read/write position deviates from the file header.
Therefore, fseek sets the position of the file pointer, and ftell calculates the number of bytes from the beginning of the file to the position obtained by fseek.
The instance code is as follows:
[Html]
Include <stdio. h>
# Include <stdlib. h>
Int main ()
{
FILE * fp;
Fp = fopen ("addoverflowDemo. c", "r ");
If (fp = NULL ){
Return-1;
}
// Int fseek (FILE * stream, long int offset, int whence); get start position
Fseek (fp, 0, SEEK_END );
// Long int ftell (FILE * stream); calculates the number of characters starting with fseek
Int value;
Value = ftell (fp );
Printf ("number of characters: % d \ n", value );
Return EXIT_SUCCESS;
}
Include <stdio. h>
# Include <stdlib. h>
Int main ()
{
FILE * fp;
Fp = fopen ("addoverflowDemo. c", "r ");
If (fp = NULL ){
Return-1;
}
// Int fseek (FILE * stream, long int offset, int whence); get start position
Fseek (fp, 0, SEEK_END );
// Long int ftell (FILE * stream); calculates the number of characters starting with fseek
Int value;
Value = ftell (fp );
Printf ("number of characters: % d \ n", value );
Return EXIT_SUCCESS;
}
The running result of the compilation connection is as follows:
[Html]
[Root @ localhost program] #./getsizeDemo
Characters: 309
[Root @ localhost program] #./getsizeDemo
Characters: 309