File operations under Linux (C + +) Open, fopen, and Freopen

Source: Internet
Author: User
Tags fread function prototype stdin

File operations under Linux (C + +) Open, fopen, and Freopen


Open is the underlying system call function under Linux, the standard I/O library functions under fopen and Freopen C/s, with input/output buffering.
Linxu under the fopen is the open encapsulation function, fopen is finally to invoke the underlying system call open.
So under Linux it is assumed that there is a need for clear control of the device. It's best to use the underlying system call (open),


open corresponding file operations are: Close, read, Write,ioctl and so on.
fopen corresponding file operations are: fclose, Fread, Fwrite, Freopen, fseek, Ftell, rewind and so on.
Freopen functions for redirecting input and output streams, which can change the input and output environment without changing the original code. However, the use should ensure that the flow is reliable. See section 3rd for details.

--------------------------------------------------------------------------------------------------------------- ----
The difference between open and fopen:
The 1,fread is buffered and read without buffering.
2,fopen is defined in standard C, and open is defined in POSIX.
3,fread can read a structure. Read in Linux/unix There is no difference between reading binary and ordinary files.
4,fopen cannot specify permissions to create a file. Open is able to specify permissions.
5,fopen returns the file pointer, open returns the file Description descriptor (integer).
No matter what equipment in 6,linux/unix is a file, can use Open,read.

----------------------------------- --------------------------------------------------------------------------------

1, open system call (Linux)
need to include header file : #include <sys/types.h>
                            #include <sys/stat.h>
        & nbsp                   #include <fcntl.h> 

function Prototypes :int Open (const char * pathname, int oflags);
int Open (const char * pathname,int oflags, mode_t mode);

Mode used only when a new file is created. Used to specify access permissions for the file.

Pathname is the pathname of the file to open/create.

The oflags is used to specify the open/create mode of the file, which can be logically or constituted by the following constants (defined in fcntl.h).
o_rdonly Read-only mode
O_wronly only Write mode
O_RDWR Read/write mode
The above three are mutually exclusive, that is, can not be used at the same time.

When you open/create a file. At least one of the three constants above must be used.

The following constants are selected:
O_append each write operation to the end of the file
O_creat If the specified file does not exist, create this file
O_EXCL assumes that the file to be created already exists, returns-1, and changes the value of the errno
O_trunc assumes that the file exists and opens in a write/read-only manner, clears all the contents of the file
O_noctty assume that the path name is pointing to the end device, do not use this as a control terminal.
O_nonblock assumes that the path name points to the fifo/block file/character file, the open and subsequent I/O of the file are set to non-clogging mode (nonblocking).


The following is used for synchronous input and output
O_dsync wait for physical I/O to finish before write. Does not wait for the file property to be updated without affecting the reading of the newly written data.
O_rsync read waits for all writes to the same region to complete before
O_sync wait for physical I/O to finish before write, contains I/O for update file properties


When you use an open call with the o_creat flag to create a file, you must use an open invocation with 3 parameter formats .

The third parameter mode is a number of flags that are either bitwise or later obtained,
These flags are defined in the header file sys/stat.h. For example, see the following:
S_IRUSR: Read permission, file owner
S_IWUSR: Write permission, file owner
S_IXUSR: Run permissions, file owner
S_IRGRP: Read permission, group to which the file belongs
S_IWGRP: Write permission, group to which the file belongs
S_IXGRP: Run permissions. Group to which the file belongs
S_iroth: Read permissions, other users
S_iwoth: Write permissions, other users
S_ixoth: Run permissions. Other users

return value : Successful returns the file description descriptor.  otherwise returns-1. Returns the file description descriptor (integer variable 0~255). The file description descriptor returned by open must be the least descriptive descriptor that the process has not yet used. Only one permission is allowed to return-1.


Error code : (both begin with E, remove it is the abbreviation for the word or word about the wrong aspect)
Eexist The pathname refers to a document that already exists, but uses the o_creat and O_EXCL flags.
Eaccess The pathname refers to a file that does not meet the required test permissions.


Erofs files to test write permissions exist in a read-only file system.

Efault The pathname pointer is out of the accessible memory space.

EINVAL the number of references mode is wrong.
Enametoolong The number of pathname is too long.

Enotdir parameter pathname is not a folder.
Enomem core memory is low.


Eloop parameter Pathname There are too many symbolic connection problems.


EIO I/O access error.


------------------- ------------------------------------------------------------------------------------------------
ssize_t write (int fd, const void *buf, size_t count);
Number of parameters :   
FD : A descriptive narrative of the file to be written.
buf : Buffer required to output
count : Maximum Output byte count  

return value : The number of bytes written successfully returned, error 1 and set errno
-----------------------------------------------.--------------------------------------------------------------- -----
ssize_t Read (int fd, void *buf, size_t count);
number of references :
buf: Buffer to read
Count: Maximum read byte count

return Value: the number of bytes read successfully returned, error 1 and set errno, assuming that the end of the file has been reached before the read. Then this time read returns 0 .   

--------------------------------------------------------------------------------------------------------------- ----


2. fopen library function
header Files :<stdio.h>
function Prototypes :FILE * fopen (const char * path, const char * mode);
The path string includes the file path and file name to open, and the parameter mode string represents the flow pattern.


Mode has the following pattern strings:
"R" or "RB" opens the file in a read-only manner, and the file must exist.
"W" or "WB" opens the file in write mode and truncates the file length to zero.
"A" or "AB" opens the file in writing, and the new content is appended to the end of the file.
"r+" or "rb+" or "r+b" open (Read and write) in an updated manner
"w+" or "wb+" or "W+b" are opened in an updated manner, and the length of the file is truncated to zero.


"A +" or "ab+" or "A+b" is opened in an updated manner. New content is appended to the end of the file.


The letter B represents a binary file instead of a text file when the file is in. (Linux does not differentiate between binaries and text files)
return value : The file pointer to the stream will be returned when the file is opened successfully. Null is returned if the file open fails. and the error code exists in the errno.

--------------------------------------------------------------------------------------------------------------- ----
freadis a function. Reads data from a file stream, reading up to count elements, each element size byte, assuming that the call successfully returns the number of elements actually read. It is assumed to be unsuccessful or read to the end of the file return 0.
function Prototypes:size_t fread (void *buffer, size_t size, size_t count, FILE *stream);
number of references:
Buffer: The memory address used to receive data
size: The number of bytes to read and write. Unit is byte
Count: The number of size bytes of data items to read and write, and each element is a size byte.
Stream: input stream
return value: The number of elements actually read. Assuming that the return value is not the same as count, the end of the file or an error may occur, getting an error message from Ferror and feof, or whether the test has reached the end of the file.
--------------------------------------------------------------------------------------------------------------- ----
fwrite:Write a data block to a file
function Prototypes:size_t fwrite (const void* buffer, size_t size, size_t count, file* stream);
number of references:
Buffer: is a pointer to fwrite. Is the address to get the data.
size: The single-byte number to write to the content.
Count: The number of data items to write to the size byte;
Stream: target file pointer;
return value: Returns the number of data blocks actually written
--------------------------------------------------------------------------------------------------------------- ----
Fflush: Writes out all the data in the file stream immediately.


function prototype : int fflush (FILE *stream);
----------------------------------------------------------------------------------------------------------- --------
fseek : is the Lseek system calls the appropriate file stream function. It specifies the location for the next read and write operation in the file stream.
function prototype : int fseek (FILE *stream, long offset, int fromwhere);
is the file pointer
" parameter offset is the offset, A positive number indicates a forward offset. Negative numbers indicate negative offset
parameters fromwhere Set the offset from where the file starts, possibly with a value of: Seek_cur, Seek_end, or Seek_set
Seek_set: File start
Seek_cur: Current position
Seek_end: End of File
Seek_set , Seek_cur and Seek_end are 0, 1, and 2 in turn.
return value : Assuming the run succeeds, the stream will point to the position of offset (pointer offset) byte with Fromwhere as the base. The function returns 0. Assuming that the run fails (for example, offset exceeds the size of the file itself), the location that the stream points to is not changed. The function returns a value other than 0.

--------------------------------------------------------------------------------------------------------------- ----

Below is the Linux next open file and display the file contents of the program:

#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <   string.h> #include <sys/types.h> #include <sys/stat.h>char * file_name = "/home/hzg/uart/download.bin";    unsigned char file_buffer[20];int main () {file * FILE_FD;    int Read_len, I;    FILE_FD = fopen (file_name, "RB");    if (file_fd = = NULL) {perror ("errno");    } else {printf ("File Open successed!\n");              } while (1) {Read_len = Fread (File_buffer, 1, FILE_FD);           if (Read_len = =-1) {printf ("File read error!\n");           Perror ("errno");       Exit (0);           } else if (Read_len = = 0) {printf ("File read over!\n");       Break           } else {printf ("Read%d Byte from Download.bin:", Read_len);           for (i = 0; i < Read_len; i++) {printf ("%02x", File_buffer[i]);       } printf ("\ n");     }      Usleep (20000);    } fclose (FILE_FD);  return 0;}

3, Freopen
function Prototypes:file * freopen (const char * filename, const char * mode, FILE * stream);
number of references
filename: The name of the file to open
Mode: the mode in which the file opens. and the pattern in fopen (r/w) is also
Stream: File pointers, typically using standard stream files (stdin/stdout/stderr)
return value: If successful, the pointer to the stream is returned, otherwise null.


function : functions for redirecting input and output streams. Redirects the standard input, output, error, or file stream in the stream to the contents of the filename file.

Linux requires redirected output very easy to use./Program name >test (>>test append), input and output redirection under Windows can use Freopen.

Usage: because the file pointer uses a standard stream file, we can not define a file pointer.

we use the Freopen () function to open the input file test.in in a read-only manner, R (read). freopen ("test.in", "R", stdin);

The input of the program is converted from the standard input stream stdin to the input from the file "Test.in".

then use the Freopen () function to write in W (write) to open the output file Test.out,freopen ("Test.out", "w", stdout);
The output of the program will be changed from the original standard output to the file "Test.out"


File operations under Linux (C + +) Open, fopen, and Freopen

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.