Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the common file manipulation functions in C language?

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces you to C language common file operation function what, the content is very detailed, interested friends can refer to, hope to help everyone.

1. Opening and closing of files 1. File pointer

Each file used has a corresponding file information area in memory, which is used to store information about the file (such as the name of the file, the status of the file, and the current location of the file). This information is stored in a struct variable. The structure type is system-declared and named FILE.

The stdio.h header file provided by the vs2013 compilation environment has the following file type declarations:

struct _iobuf { char *_ptr; int _cnt; char *_base; int _flag; int _file; int _charbuf; int _bufsiz; char *_tmpfname;};typedef struct _iobuf FILE;

Whenever a file is opened, the system will automatically create a FILE structure variable according to the file situation, and fill it with information, generally through a FILE pointer to maintain this FILE structure variable, so it is more convenient to use.

Here we can create a pointer variable to FILE*:

FILE* pf;//file pointer variable

The file pointer variable can be used to find the file associated with it.

2. File opening and closing

Files need to be opened before reading and writing, and closed after use.

Specify fopen to open files and fclose to close files.

//Open file FILE* fp=fopen(const char* filename,const char* mode);//Two parameters: open file name and open mode//Close file fcolse(fp);//Open file FILE* fp=fopen(const char* filename,const char* mode);//Two parameters: open file name and open mode//Close file fcolse(fp);

Common ways to open files are as follows:

file open meaning specifies that the file does not exist "r"(read only) in order to input data, open a text file error "w"(write only) in order to output data, open a text file to create a new text file "a"(append) add data to the end of the file text error "rb"(read only) in order to input data, open a binary file error "wb"(write only) in order to output data, Open a binary file Create a new binary file "ab"(append) Error adding data to end of binary file

An example of an open close text file is as follows:

The file is opened in write-only mode. When the text file does not exist under the code path, the program will automatically generate a new file; if the file is opened in read-only mode, when the text file does not exist, the program will display open failure after running.

#includeint main(){ FILE* fp = fopen("text1.txt", "w");//Open file text if (fp == NULL)//Determine whether the opening is successful { printf("Open File Error\n"); return; } fclose(fp); return 0;} Second, the order of the file read and write function name applicable range character input function fgetc all input stream character output function fputc all output stream text line input function fgets all input stream text line output function fputs all output stream formatting input function fscanf all input stream formatting output function fprintf all output stream binary input function fread file binary output function fwrite file 1, fgetc() and fputc() functions

The fgetc() function reads a character from the specified file, reads to the end of the file, or returns EOF if the read fails.

The fputc() function is used as follows:

int fputc(int ch,FLEF* fp);

ch is the character to write, fp is the file pointer.

Note: For each character written, the pointer to the internal position of the file moves backward one byte.

fgets() and fputs() functions

The fgets() function is used as follows:

char* fgets(char* buf,int n,FILE* fp);

buf is the address where the string is stored, n is the length of the string to read, fp is the pointer to the file. This function can read only one line at a time, and stops reading if\nthere are multiple lines that need to be read cyclically.

The fputs() function is used as follows:

int fputs(const char* str,FILE* fp);

str is the string to write to the file, fp is the file to operate on, and a return value of 0 indicates success. The string to be written also ends with\n, so multi-line writing requires repetition.

fscanf() and fprintf() functions

The fscanf() and fprintf() functions are similar to the scanf() and printf() functions used earlier, both formatting read and write functions, the difference between the two is that fscanf() and fprintf() functions read and write objects not keyboard and display, but disk files.

The two function prototypes are:

int fscanf(FILE* fp,char* fromat,……);int fprintf(FILE* fp,char* format,……);

Compared to scanf() and printf(), there is only one more fp parameter.

Fread() and fwrite() functions

(1)fread() function

Used to read binary data

size_t fread(void* buf,size_t size,size_t count,FILE* fp);

fread returns the number of complete items actually read, which may be less than the count if an error occurs or if the end of the file is encountered before the count is reached. Use feof or ferror functions to distinguish between read errors and end-of-file conditions. If the size or count is 0, fread returns 0 and the buffer contents remain unchanged.

buf is a pointer to a memory block used to store the read data.

Size represents the number of bytes per data block.

Count represents the number of blocks to read.

FP file pointer.

(2) fwrite() function

size_t fwrite(const void* buf,size_t size,size_t count,FILE* fp);

fwrite returns the number of complete entries actually written, which may be less than count if an error occurs. buf is used to store the data to be written, and the rest of the parameters are the same as fread().

3. Random reading and writing of files 1. fseek function

Locating file pointers based on file pointer position and offset

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

The first parameter is the file pointer; the second parameter is the offset, a positive number indicates the right offset, a negative number indicates the left offset; the third parameter sets where the offset starts from the file, and may take values: SEEK_CUR, SEEK_END, SEEK_SET.

SEEK_SET: Start of file

SEEK_GUR: Current location

SEEK_END: End of file

SEEK_SET, SEEK_CUR and SEEK_END are 0, 1 and 2 respectively.

2. Ftell function

Calculates the offset of the file pointer from the starting position

long int ftell(FILE* stream);3. rewind function

Return the file pointer to the beginning of the file

void rewind(FILE* stream); IV. Text files and binary files

Data files are divided into text files and binary files.

Binary file: Data stored in memory in binary form, output to external memory without conversion.

Text file: A file stored in ASCII characters. If you want to store it in ASCII format on external storage, you need to convert it before storing it.

Storage of data in memory: Characters are stored in ASCII form; numeric data can be stored in ASCII or binary form.

Example: positive number 10000, output to disk in ASCII format, takes up five bytes (one byte per character); output in binary format, takes up only four bytes on disk.

V. Determination of End of File Reading

feof() function is used to determine whether the internal pointer to the file points to the end of the file, when pointing to the end of the file returns a non-zero value, otherwise returns a zero value.

ferror() function is used to determine whether the file operation error, error returns non-zero value, otherwise returns zero value.

Note: During file reading, you cannot use the return value of feof() function to directly determine whether the file is finished. Instead, it applies to determining whether the end of a read failure or the end of a file is encountered when the file read ends.

1. Whether the text file reading is finished, determine whether the return value is EOF(fgetc) or NULL(fgets)

For example:

fgetc determines whether it is EOF

fgets Determines whether the return value is NULL.

2, binary file reading end judgment, to determine whether the return value is less than the actual number to read.

For example:

fread determines whether the return value is less than the actual number of reads.

VI. File buffer

Data output from memory to disk is sent to buffers in memory, filled and sent to disk together. If data is read from disk like a computer, the data is read from disk files into memory buffers (full buffers), and then the data is sent from the buffer to the program buffer one by one.

#include #include int main(){ FILE*pf = fopen("test.txt", "w"); fputs("abcdef", pf);//put code in output buffer first printf("Sleep for 10 seconds-data has been written, open test.txt file, found that the file has no content\n"); Sleep(10000); printf("Refresh buffer\n"); ffflush (pf);//only write data from output buffer to file (disk) when flushing buffer //Note: ffrush is no longer available on older versions of VS printf("Sleep for another 10 seconds-at this point, open the test.txt file again, the file has content\n"); Sleep(10000); fclose(pf); //Note: fclose also flushes the buffer when closing a file pf = NULL; return 0;}

Because of the buffer, C needs to flush the buffer with the ffrush function or close the file at the end of the file operation.

About C language common file operation function what to share here, hope the above content can have some help to everyone, can learn more knowledge. If you think the article is good, you can share it so that more people can see it.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report