C language file positioning: Use of fseek () and ftell () Functions

Source: Internet
Author: User

The fseek function is used to set the current read/write location of a file:

Function prototype: int fseek (File * FP, long offset, int origin );
Function: moves the FP file read/write position pointer to the specified position.

 

Fseek (FP, 20, seek_set );

// Indicates that the pointer to the read/write position of the FP file is removed 20 bytes after the file starts.

The ftell function is used to obtain the current read/write location of a file;
Function prototype: Long ftell (File * FP)
Function: Obtain the current read/write position of the stream file. The returned value is the number of bytes that the current read/write position deviates from the file header.

 

Ban = ftell (FP );

// Obtain the current read/write location of the file specified by FP and pass the value to the variable ban.

Comprehensive application of fseek and ftell functions:
Analysis: You can use the fseek function to move the position pointer to the end of the file, and then use the ftell function to obtain the number of bytes from the file header. This number is the length of the file.

# Include <stdio. h> main () {file * FP; char filename [80]; long length; printf ("input the file name:"); gets (filename ); fp = fopen (filename, "rb"); If (FP = NULL) printf ("file not found! /N "); else {fseek (FP, ol, seek_end); length = ftell (FP); printf (" the file length % 1D Bytes/N ", length ); fclose (FP );}}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.