Differences between standard I/O and file I/O

Source: Internet
Author: User

Differences between standard I/O and file I/O

1. Definition
Standard IO: Standard I/O is a standard I/O model established by ANSI C. It is a quasi-function package and defined in the stdio. h header and has certain portability. The standard IO library handles a lot of details. For example, cache allocation to optimize the length of IO execution. Standard IO provides three types of cache.
(1) Full cache: actual IO operations are performed only when the standard I/O cache is filled.
(2) Row cache: when a new line character is encountered in the input or output, the standard IO library performs IO operations.
(3) Without Caching: stderr.

File IO: file IO is called an IO without cache (unbuffered I/O ). Without caching, each read and write calls a system call in the kernel. That is, the basic IO service provided by the operating system, which is generally referred to as low-level I/O, is bound to the OS, which is specific to the * nix platform.
2. Differences
First, a significant difference between the two is that the standard I/O uses a buffer mechanism by default. For example, calling the fopen function not only opens a file, in addition, a buffer is created (two buffers are created in read/write mode), and a data structure (FILE *) containing FILE and buffer-related data is created *). Low-level I/O generally does not use buffering, and you need to create a buffer yourself. However, in * nix systems, kernel buffering technology is used to improve efficiency, read/write invocation refers to data replication between the kernel buffer and the process buffer. You do not need to maintain the buffer by yourself when using standard IO. The standard IO library selects the buffer type based on stdin/stdout, that is, when you use standard IO, you need to know the type of stdin/stdou and its default buffer mode. If not, you need to set it with setvbuf before using it, for example, the standard input and output types of a collaborative process are both pipelines, so the default buffer type is full buffering. To use standard IO, you need to set row buffering. For file IO, as long as you can maintain the buffer well, no standard IO is required.
Secondly, the file I/O is mainly for file operations, read/write hard disks, and standard I/O, mainly for printing and output to the screen. Because their devices are different, file I/O is for files, standard I/O is for the console, and operation is for the ghost stream. Different devices have different features and must have different APIs for optimal access.
Finally, let's look at the functions they use.
  

1. fopen and open
Standard I/O open a FILE using the fopen function: FILE * fp = fopen (const char * path, const char * mode)
Path is the file name, and mode is used to specify the string of the file opening mode, such as "r", "w", "w +", "a", etc, you can add the letter B to specify to open the FILE in binary mode (for * nix systems, there is only one FILE type, so there is no difference). If the FILE is opened successfully, a FILE pointer is returned, if NULL is returned for failure, the file pointer here does not point to the actual file, but a data packet about the file information, including the buffer information used by the file.
* The nix system uses the open function to open a file: int fd = open (char * name, int how );
Similar to fopen, name indicates the file name string, while how specifies the open mode: O_RDONLY (read-only), O_WRONLY (write only), O_RDWR (readable and writable ), for other modes, please use man 2 open. A positive integer is called a file descriptor. This is significantly different from standard I/O. If a positive integer fails,-1 is returned, which is different from standard I/O.

2. fclose and close
In contrast to opening a file, standard I/O uses fclose to close the file and pass in the file pointer. If the file is closed successfully, 0 is returned; otherwise, EOF is returned.
For example:
If (fclose (fp )! = 0)
Printf ("Error in closing file ");

* Nix uses close to close open files, which is similar to fclose, except that when an error occurs,-1 is returned instead of EOF. If an error is closed successfully, 0 is returned. The traditional method of using error code in C language for error handling.

3. read files: getc, fscanf, fgets, and read
Getc can be used to read files in standard I/O. gets can be used to read files by one character or by one character) and fgets are read in string units (after the first line break character encountered). gets (accepts a parameter, file pointer) does not determine whether the target array can accommodate the characters to be read, storage overflow may occur (not recommended), while fgets uses three parameters char * fgets (char * s, int size, FILE * stream). The first parameter is the same as gets, used to store the input address. The second parameter is an integer, indicating the maximum length of the input string. The last parameter is the file pointer pointing to the file to be read. Finally, fscanf is similar to scanf, but a parameter is added to the file used to specify the operation, such as fscanf (fp, "% s", words)
* In the nix system, the read function is used to read files opened by the open function. The function prototype is as follows:
Ssize_t numread = read (int fd, void * buf, size_t qty );

Fd is the file descriptor returned by open. buf is used to store the destination buffer, while qty specifies the number of bytes to read. If the read is successful, the number of bytes (less than or equal to qty) is returned ).

4. Determine the end Of the file
If the read Attempt reaches the end of the file, the getc of the standard IO will return a special value of EOF, while the fgets will return NULL when it encounters EOF, and for * nix read functions, the situation is different. The read function reads the specified number of bytes, and the final data to be read may not have as many qty as you need (qty). If the read function returns 0 after the read end.

5. write files: putc, fputs, fprintf, and write
In contrast to reading files, the standard C language I/O uses putc to write characters, such as putc (ch, fp). The first parameter is a character, and the second is a file pointer. Fputs is similar to this: fputs (buf, fp); only the first parameter is replaced with a string address. Like printf, fprintf adds a parameter to specify the file to be written, for example, fprintf (stdout, "Hello % s. \ n "," dennis "); remember that fscanf and fprintf use the FILE pointer as the first parameter, while putc and fputs are the second parameter.
The write function is provided in * nix System for writing files. The prototype is similar to read: ssize_t result = write (int fd, void * buf, size_t amt); fd is the file descriptor, buf is the memory data to be written, and amt is the number of bytes to be written. If the write is successful, the number of written bytes is returned. The result can be compared with amt to determine whether the write is normal. If the write fails,-1 is returned.

6. Random Access: fseek (), ftell (), and lseek ()
Standard I/O uses fseek and ftell for random FILE access. First, let's look at the fseek function prototype int fseek (FILE * stream, long offset, int whence). The first parameter is the FILE pointer, the second parameter is a long offset, indicating the distance from the start point. The third parameter is the pattern used to specify the starting point. stdio. h specifies the following pattern constants:
Start of SEEK_SET File
Current location of SEEK_CUR
End of SEEK_END File
Let's look at several call examples:
Fseek (fp, 0L, SEEK_SET); // locate the start of the file
Fseek (fp, 0L, SEEK_END); // locate the end Of the file
Fseek (fp, 2L, SEEK_CUR); // Move the current position of the file two bytes forward
The ftell function is used to return the current position of the object. The return type is a long type, for example, the following call:
Fseek (fp, 0L, SEEK_END); // locate to the end
Long last = ftell (fp); // returns the current position
At this time, the last value is the number of bytes of the file pointed to by the file pointer fp.
Similar to standard I/O, * nix provides lseek to implement fseek. The prototype is as follows:
Off_t lseek (int fildes, off_t offset, int whence); fildes are file descriptors, and offset is offset. whence is also the starting point mode. The only difference is that lseek has returned values, if the operation succeeds, the position before the pointer change is returned. Otherwise,-1 is returned. The value of whence is the same as that of fseek: SEEK_SET, SEEK_CUR, and SEEK_END, but it can also be replaced by integers 0, 1 and 2.

Fseek and ftell = lseek;

 

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.