A summary of various file reading and writing methods in C language _c language

Source: Internet
Author: User
Tags fread function prototype

Objective
when looking for a job, once used C language practice for a period of time algorithm, but also in several also known as the OJ platform has a reliable ranking. I thought the C language was limited to practice, but one of the problems in the work made me realize the usefulness of C language was very extensive. Here, if you use C to manipulate files to save a string, and read a string. The algorithm is often printf to print out the results, but the real work often through the file to do some persistent storage work.

C-file I/O
file I/O is the focus of every language, so let me first explain how to use the C language to do file I/O operations.
Files and Streams
In the case of C-language programs, all I/O operations simply move or move the bytes out of the program. As a result, this byte stream is called a flow (stream). The program only needs to care about creating the correct output byte data and correctly interpreting the byte data read from the input. The specifics 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" are actually copying data back and forth from a memory area called buffer. Copying data back and forth from memory is very fast. The buffer used for the output stream is refreshed (flush, physically written) to the device or file only if it is full. It is more efficient to write the written output of a write-filled buffer at a single point, which is written separately from the program. The input buffer is a similar principle.
The stream is divided into two types, namely, text flow and binary stream.
Open and close a stream
The fopen function opens a specific file and associates a stream with the file. Its prototype looks like the following:
[CPP] View plaincopyprint? See the code slices on the codes derive from my Code slice

  file* Open (const char* name, const char* mode); 

The name parameters are the names of the files or devices you want to open. The mode parameter identifies whether the stream is used for read-only, write-only, read-write, or text-or binary-stream. Some common patterns are listed in the following table:

If the fopen function succeeds, it returns a pointer to the file structure that represents the newly created stream. If the function fails, it returns a null pointer, and the error prompts the nature of the problem.
The stream is closed with a function fclose, and its prototype is as follows:
[CPP] View plaincopyprint? See the code slices on the codes derive from my Code slice

  int fclose (FILE *f); 

For an output stream, the Fclose function flushes the buffer before the file is closed. If it succeeds, Fclose returns a value of 0, otherwise it returns EOF.

Since fopen and fclose are both open and closed as file structure pointers, the stdio.h header file contains a description of file structure body files. Here is a description of the file structure definition:

  struct _IOBUF { 
    char *_ptr;//Next character to be read address 
    int _cnr;//remaining char 
    *base;//buffer base address  
    int _flag;//read-write file flags bit 
    int _file;//File number 
    int _charbuf//check buffer status  
    int _bufsiz;//File size 
    char *_tmpfname;//temporary file name 
  };
   typedef struct _IOBUF FILE; 

Character I/O
when a stream is opened, it can be used for input and output. The simplest form of it is 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 stream that needs to be manipulated is passed as a parameter to getc and fgetc, but GetChar is always read from standard input. Each function reads a character from the stream and returns it as the return value of the function. If there are no more characters 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:
[CPP] View plaincopyprint? See the code slices on the codes derive from my Code slice

  int FPUTC (int character, file* stream); 
  int PUTC (int character, file* stream); 
  int Putchar (int character); 

Line I/O
row I/O can actually be performed 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 a conversion between the internal or external representations of numbers and other variables. Since the daily work is typically formatted with I/O, it does not speak fgets and fputs this unformatted I/O operation. (Of course, there is also an important reason, fgets can not judge the buffer length, easily lead to overflow, etc.)
scanf Family
the prototype of the SCANF function family is shown below. Ellipses in each prototype represent a variable-length list of pointers. Values from input conversions are stored individually to the memory location to which these pointer parameters are pointing.

  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 formatting code given by the format string. The input stops when the formatted string reaches the end, or when the read input no longer matches the type specified by the format string. In either case, the number of input values being converted is returned as the return value of the function. If the file has reached its tail before any input value is converted, the function returns the constant value EOF.
printf Family
The 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 it in binary form, and there are also useful scenarios in the Android system where binary files are used to store data in bits. Describes a function prototype that manipulates 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:
[CPP] View plaincopyprint? See the code slices on the codes derive from my Code slice

  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 saved, the size is the number of bytes per element in the buffer, count is the number of elements read or written, and the stream is the data read or written flow.
Refreshing and locating functions
There are also other functions that are useful when working with streams. First, it is fflush, which forces the data in the buffer area of an output stream to be physically written, whether it is already full or not. Its prototype looks like the following:

  int fflush (file* stream); 

This function should be used when we need to physically write out the data for the output buffer immediately.
In normal circumstances, the data is written in a linear fashion, which means that the data written later in the file is positioned behind 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 locate 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 the location in the file that needs to be positioned. The following table describes how to use the Fseek parameter.

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.