About the Usage of fseek and ftell

来源:互联网 发布:阿里云怎么修改镜像 编辑:程序博客网 时间:2024/05/16 01:50

The following is a simple program that accomplishs the division of one file into two parts, in which what should be concerned is the usage of two function, fseek and ftell.

[1] fseek
Header
<cstdio>

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

Sets the position indicator associated with the stream to a new position defined by adding offset to a reference position specified by origin.
The End-of-File internal indicator of the stream is cleared after a call to this function, and all effects from previous calls to ungetc are dropped.
When using fseek on text files with offset values other than zero or values retrieved with ftell, bear in mind that on some platforms some format transformations occur with text files which can lead to unexpected repositioning.
On streams open for update (read+write), a call to fseek allows to switch between reading and writing.

Parameters
stream
Pointer to a FILE object that identifies the stream.
offset
Number of bytes to offset from origin.
origin
Position from where offset is added. It is specified by one of the following constants defined in <cstdio>:
SEEK_SET Beginning of file
SEEK_CUR Current position of the file pointer
SEEK_END End of file

Return Value
If successful, the function returns a zero value. Otherwise, it returns nonzero value.

[2] ftell
Header
<cstdio>

long int ftell ( FILE * stream );
Get current position in stream

Returns the current value of the position indicator of the stream.
For binary streams, the value returned corresponds to the number of bytes from the beginning of the file.
For text streams, the value is not guaranteed to be the exact number of bytes from the beginning of the file, but the value returned can still be used to restore the position indicator to this position using fseek.

Parameters
stream
Pointer to a FILE object that identifies the stream.

Return Value
On success, the current value of the position indicator is returned.
If an error occurs, -1L is returned, and the global variable errno is set to a positive value. This value can be interpreted by perror.


code:


I will do appreciate what suggestion you give me, thx!