C language Read and write files

Source: Internet
Author: User
Tags fread function prototype

Preface to find work, have used C language practice over a period of time algorithm topic, also in a few also known as the OJ platform has been a reliable ranking. I thought the C language was limited to practicing the algorithm, but a problem solved in my work made me realize that the use of C was very extensive. Here's how to manipulate a file in C to save a string, and read a string. The algorithm often is printf to print out the results, but the real work often through the file to do some persistent storage work.
I/O for c-file I/O files is the focus of every language, so here's how I am going to use the C language to do my I/O to the file. Files and streams for a C language program, all I/O operations are simply things that move in or out of a program. Therefore, this byte stream is called a stream. The program only needs to be concerned with creating the correct output byte data and correctly interpreting the byte data read from the input. The details of a particular I/O device are hidden from the programmer. The vast majority of flows are fully buffered (fully buffered), which means that read and write actually replicate data back and forth from a piece of memory called the buffer. Copying data back and forth from memory is very fast. The buffer used for the output stream is flushed (flush, physically written) to the device or file only when it is full. It is more efficient to write full buffers at once and write output from the program individually.    Input buffers are similar in principle. There are two types of flows, namely text flow and binary stream. Open the stream and close the stream fopen function to open a specific file and associate a stream with this file. Its prototype is as follows:
file* Open (const char* name, const char* mode);
Name parameter is the name of the file or device you want to open. The mode parameter identifies whether the stream is used for read-only, write-only, read-write, and it is a text stream or a binary stream. Some common patterns are listed in the following table:
Read Write Add to
Text "R" "W" A
Binary "RB" "WB" "AB"
If the fopen function executes successfully, it returns a pointer to the file structure that represents the newly created stream.    If the function fails, it will return a null pointer, and error will indicate the nature of the problem. The stream is closed with the function fclose, and its prototype is as follows:
int fclose (FILE *f);
For the output stream, the Fclose function flushes the buffer before the file is closed. If it succeeds, Fclose returns a value of 0, otherwise EOF is returned.

Since fopen and fclose are both open and closed as file struct pointers, the stdio.h header contains a description of the file structure body file. Here is a description of the file struct definition:
struct _IOBUF {    char *_ptr;//The address of the next character to be read    int _cnr;//The remaining characters    char *base;//buffer base address     int _flag;//read-write file flag bit    int _file;//File number    int _charbuf;//check buffer status     int _bufsiz;//File size    char *_tmpfname;//Temp file name};typedef str UCT _iobuf FILE;
Character I/O when a stream is opened, it can be used for input and output. It is the simplest form of character I/O. Character input is performed by the GetChar function family, and their prototypes are as follows:
int fgetc (file *stream); int getc (file *stream); int getchar (void);
The flow that needs to be manipulated is passed as a parameter to getc and fgetc, but GetChar is always read from the standard input. Each function reads a character from the stream and returns it as the return value of the function.    If no more characters exist in the stream, the function returns the constant value EOF (-1). In order to write a single character to a stream, you can use the Putchar function family. Its prototype is as follows:
int FPUTC (int character, file* stream), int putc (int character, file* stream), int putchar (int character);
Line I/O line I/O can actually be executed in two ways-unformatted or formatted. Both of these forms are used to manipulate strings. The difference is that unformatted I/O simply reads or writes strings through fgets and fputs, while formatted I/O performs conversions between the internal or external representations of numbers and other variables. Due to the generally formatted I/O operations in daily work, the fgets and fputs non-formatted I/O operations are not spoken here. (There is, of course, one important reason, fgets cannot judge the length of the buffer, which is prone to overflow, etc.) the scanf family scanf function family is shown below. Ellipses in each prototype represent a variable-length list of pointers. The values that are converted from the input are stored individually to the memory location pointed to by these pointer parameters.
int fscanf (file* stream, const char* format, ...); int scanf (const char* format, ...); int sscanf (const char* string, const char* format, ...);
These functions read characters from the input source and convert them according to the format code given by the format string. The input stops when the formatted string reaches the end or the input that is read does not match the type specified by the format string. In either case, the number of input values that are converted is returned as the return value of the function. If the file has reached the tail before any input values are converted, the function returns the constant value EOF.
The printf family printf function family is used to create formatted output. Their function prototypes are as follows:
int fprintf (FILE *stream, const char* format, ...); int printf (const char* format, ...); int sprintf (char* buffer, const char* format, ...);
Binary I/o the most efficient way to write data to a file is to write in binary form, and the Android system also has a very useful binary file to store data in bits.    Describes the function prototypes that manipulate binary I/O. The Fread function is used to read binary data, and the Fwrite function is used to write binary data. Their prototypes are as follows:
size_t fread (void* buffer, size_t size, size_t count, file* Stream); size_t fwrite (void* buffer, size_t size, size_t count, file* stream);
Buffer is a pointer to the memory location where the data is stored, size is the number of bytes per element in the buffer, count is the number of elements read or written, and stream is the data read or write flow. The refresh and positioning functions are also useful when working with streams, among other functions. First, it is fflush, which forces the data in the buffer area of an output stream to be physically written, whether or not it is already full. Its prototype is as follows:
int fflush (file* stream);
This function should be used when we need to physically write the data of the output buffer at once.
Under normal circumstances, the data is written in a linear manner, which means that the data written later in the file is positioned after all previously written data. C also supports random access I/O, which means accessing different locations of files in any order. Random access is achieved by locating the desired location in the file before reading or writing. The Fseek function is generally used to implement the function prototype as follows:
int fseek (file* stream, long offset, int from);
The Fseek function allows you to position in a stream. This action will change the next read or write location. Its first parameter is the stream that needs to be changed, and its second and third parameters identify where the file needs to be located. The following table describes how the fseek parameter is used.
If the From IS You will be positioned to
Seek_set Offset characters from the beginning of the stream, offset must be a non-negative value
Seek_cur Offset characters from the current position of the stream, offset can be positively negative
Seek_end The offset value can be positively negative from the trailing position of the stream. is a positive number, it is positioned behind the end of the file


C language Read and write files

Related Article

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.