Get the App
SLTechnology News&Howtos  ›  Development  › 

Analysis of C language File Operation

Shulou Source: shulou.com Published: 2022-06-02 16:45:33 10月01日 Update

This article introduces the relevant knowledge of "C language file operation analysis". In the operation of actual cases, many people will encounter such a dilemma. Next, let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Random reading and writing of files

The previous function can only read and write sequentially, while random read and write requires the fseek function to locate the file pointer according to the location and offset of the file pointer.

Fseek function

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

Return value: if 0 is returned successfully, a non-0 value is returned.

Parameter: stream is the file pointer and offset is the offset. Origin is the starting position, and there are three types of SEEK_SET (the location at the beginning of the file), SEEK_END (the location at the end of the file), and SEEK_CUR (the current position of the file pointer).

Example: hello world is put in the test.txt file

Ftell function

Long int ftell (FILE* stream)

Returns the offset of the file pointer from the starting position

Rewind function

Void rewind (FILE* stream)

Let the pointer of the file return to the starting position of the file

File end decision

1. Whether the reading of the text file is finished, and determine whether the return value is EOF or NULL

For example, fgetc judges EOF and fgets judges NULL

EOF or NULL is returned when reading fails and when the file ends.

two。 The reading end of the binary file is judged to determine whether the return value is less than the actual number to be read.

For example, fread determines whether the returned value is less than the actual number to be read.

When the file reading ends, use the ferror function and the feof function to check whether the reason for the end of the file reading is the end of the read failure or the end of the file.

Feof function and ferror function

Int feof (FILE* stream)

Returns a non-zero value if the end of the EOF read is encountered, otherwise 0 is returned.

Int ferror (FILE* stream)

If a read error occurs, a non-zero value is returned, otherwise 0.

Example of determining the end of a text file:

This is the end of the content of "C language File Operation Analysis". Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Tags: File function location pointer start actual offset language analysis number content text more end knowledge positioning practical successful successful next Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Xiaomi macOS Shulou Tech Info Apple MySQL