Simple parsing of fopen/open, read/write and fread/fwrite

Source: Internet
Author: User
Tags fread

Because I recently saw an interview question about file copying, I found that I do not know much about open and fopen, So Baidu Google is charging online, in UNIX environments, C has two sets of teams for reading and writing binary stream files: 1)
Fopen, fread, fwrite; 2) Open, read, write

Here is a brief introduction of their differences.

Differences between open and fopen:

1. Buffer File System

The buffer file system features a "buffer" in the memory, which is used for every file in the program. When reading a file, read data from a disk file into the memory "buffer" first, and then read the received variables from the memory "buffer. When writing a file, the data is first written to the memory "buffer", and then written to the file after the memory "buffer" is filled up. It can be seen that the size of the memory "buffer" affects the number of external memory operations. The larger the memory "buffer", the less times the external memory operations are performed, fast execution speed and high efficiency. Generally, the size of the file "buffer" varies with the random device.

Fopen, fclose, fread, fwrite, fgetc, fgets, fputc, fputs, freopen, fseek, ftell, rewind, etc.

Some function definitions:

Int fputc (int ch, file * stream );

Int fgetc (File * stream );

Int fseek (File * stream, long offset, int fromwhere );



2. Non-buffered File System

The buffer file system uses the object structure pointer to manage the file. The file pointer can be used to access the file. It can read and write characters, strings, formatted data, and binary data. The non-buffered file system depends on the operating system. It reads and writes files through the operating system function. It is a system-level input and output. It does not have a file structure pointer and can only read and write binary files, however, it is highly efficient and fast. Since ANSI standards do not include non-buffered file systems, we recommend that you do not select them. This book is only a brief introduction. Open, close, read, write, GETC, getchar, putc, putchar, etc.


Open is the file handle returned by the system call. The file handle is the index of the file in the file description table, fopen is the library function of C, and a pointer to the file structure is returned.

Fopen is a C language library function in the ansic standard. Different kernel APIs should be called in different systems.


In Linux, the system function is open, and fopen is its encapsulation function. For reference only.

File descriptor is a concept in Linux. All devices in Linux operate as files, such as network sockets and hardware devices. Including operation files.

Fopen is a standard C function. Return the file stream instead of the file handle in Linux.

A device file cannot be used as a stream file.

Fopen is used to manipulate regular files and has buffer. It is different from open.

Use fopen to open a common file and open a device file.

Fopen is in Standard C, while open is a Linux system call.

Their levels are different.

Fopen can be transplanted, open cannot

The main difference between fopen and open is that fopen has a cache in the user mode, which reduces switching between the user mode and the kernel mode during read and write operations, while open requires switching between kernel and user States every time. The result is that if files are accessed sequentially, fopen functions are faster than calling open functions directly; if the random access to file open is faster than fopen.

The former is a low-level Io, and the latter is a high-level Io.

The former returns a file descriptor (in the user program area), and the latter returns a file pointer.

The former has no buffer, and the latter has a buffer.

The former works with read and write, and the latter works with fread and fwrite.

The latter is expanded based on the former. In most cases, the latter is used.

Example:

Function Name: fopen
Function: open a stream
Usage: file * fopen (char * filename, char * type );
Program example:

# Include <stdlib. h>
# Include <stdio. h>
# Include <dir. h>

Int main (void)
{
Char * s;
Char Drive [maxdrive];
Char dir [maxdir];
Char file [maxfile];
Char ext [maxext];
Int flags;

S = getenv ("comspec");/* Get the comspec Environment Parameter */
Flags = fnsplit (S, drive, Dir, file, ext );

Printf ("command processor info: \ n ");
If (flags & drive)
Printf ("\ tdrive: % s \ n", drive );
If (flags & directory)
Printf ("\ tdirectory: % s \ n", DIR );
If (flags & filename)
Printf ("\ tfile: % s \ n", file );
If (flags & Extension)
Printf ("\ textension: % s \ n", ext );

Return 0;
}

Function Name: Open
Function: open a file for reading or writing.
Usage: int open (char * pathname, int access [, int permiss]);
Program example:

# Include <string. h>
# Include <stdio. h>
# Include <fcntl. h>
# Include <Io. h>

Int main (void)
{
Int handle;
Char MSG [] = "Hello World ";

If (handle = open ("test. $", o_creat | o_text) =-1)
{
Perror ("error :");
Return 1;
}
Write (handle, MSG, strlen (MSG ));
Close (handle );
Return 0;
}

PS:

1. The fopen series are standard C-library functions; the open series are defined by POSIX and are
Call.

That is to say, the fopen series are more portable, while the Open series can only be used in POSIX operating systems.

2. When using fopen functions, You need to define an object that refers to a file.
Handler) is a struct, while the Open series uses an int integer called "file descriptor.

3. The fopen series are high-level I/O, and buffer is used for reading and writing. The Open series are relatively low-level, closer to the operating system, and there is no buffer for reading and writing. Because they can deal with more operating systems, the Open series can access and change some information that cannot be accessed by the fopen series, such as viewing the read and write permissions of files. These additional features are generally system-specific.

4. "# include <sdtio. h>" is required to use fopen functions. "# include
<Fcntl. h> ", use libc (-LC)

 

Difference between read/write and fread/fwrite

1. fread is buffered, and read is not buffered.

2. fopen is defined in standard C, and open is defined in POSIX.

3. fread can read a structure. There is no difference between reading binary files in Linux/Unix.

4. fopen cannot specify the permission to create a file. Open can specify the permission.

5. fopen returns the pointer and open returns the file descriptor (integer ).

6. If any device in Linux/Unix is a file, you can use open or read.

If the file size is 8 K. If you use read/write and only allocate 2 k cache, You need to perform four system calls to read the file from the disk.

If you use fread/fwrite, the system automatically allocates the cache and reads the file as long as one system call is read from the disk.

That is, read/write is used to read the disk four times, while fread/fwrite is used to read the disk only once. It is 4 times more efficient than read/write.

If the program has a limit on the memory, it is better to use read/write.

Fread and fwrite are used to automatically allocate the cache, which is faster and easier than doing it on your own. If you want to process some special descriptors, use read and write, such as a set of interfaces and pipelines.

The efficiency of calling write by the system depends on the size of your Buf and the total number of writes you want to write. If the Buf is too small, the number of times you enter the kernel space increases greatly, resulting in low efficiency. Fwrite caches the data for you to reduce the number of system calls that actually occur, so the efficiency is relatively high.

Summary:

In general, in order to make the program more portable, The fopen series is the first choice without having to use features that cannot be implemented by the fopen series.

 

 

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.