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 ultimately to call the underlying system call open.
So under Linux, if you need to have explicit control over your 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 that redirect input and output streams, which can change the input and output environment without changing the original code, but should be used to 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 normal files.
4,fopen cannot specify permissions to create a file. Open can specify permissions.
5,fopen returns the file pointer, open returns the file descriptor (integer).
Any device in 6,linux/unix is a file and can be used 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 to specify access permissions for the file.

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

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

when opening/creating a file, use at least one of the three constants above. The following constants are selected:
   o_append         Each write is written to the end of the file  
   o_creat             If the specified file does not exist, create this file  
  &NBSP;O_EXCL           &NBSP ;   returns 1 if the file to be created already exists, and modifies the value of errno
   o_trunc           If the file exists and is opened in write/read-only mode, clear Empty file full content  
   o_noctty         If the pathname points to the end device, do not use this as a control terminal.
   o_nonblock   If the pathname points to a fifo/block file/character file, the open and subsequent I/O of the file are set to non-blocking (nonblocking mode).
//The following 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. &NBSP
   o_rsync          read wait for all writes to the same region to complete before
   o_sync             Wait for physical I/O to end and write, including I/O to update file properties


When you use "color: #ff0000" with flag is used to create a file, you must use an open call with . The third parameter mode is a bitwise OR after several flags,
These flags are defined in the header file Sys/stat.h, as follows:
  S_IRUSR:     Read permissions, file owner
  S_IWUSR:   Write permissions, file owner
  S_IXUSR:     Execute permissions, file owner
  S_IRGRP:     Read permissions, file belongs to group
  S_IWGRP:   Write permissions, the file belongs to group
  S_IXGRP:     Execute permissions, file belongs to group
  S_iroth:   Read permission, other users
  S_iwoth:   Write permissions, other users
  S_ixoth:   Execute permissions, other users

return value : succeeds returns the file descriptor, otherwise returns-1. Returns the file descriptor (integer variable 0~255). The file descriptor returned by open must be the smallest descriptor that the process has not yet used. Returns 1 as long as one of the permissions is disabled.
Error code : (both begin with E, remove it is the abbreviation for the word or word about the wrong aspect)
The eexist parameter pathname refers to a file that already exists, but uses the o_creat and O_EXCL flags.
The eaccess parameter pathname refers to a file that does not meet the required test permissions.
Erofs files to test write permissions exist in the read-only file system.

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

The EINVAL parameter mode is incorrect.
enametoolong parameter pathname too long.

The Enotdir parameter pathname is not a directory.
Enomem core memory is low.
The Eloop parameter pathname has too many symbolic connection problems.
EIO I/O access error.


------------------------------- ------------------------------------------------------------------------------------
ssize_t Write (int fd, const void *buf, size_t count);
parameter :   
FD : The file descriptor to write.
buf : Buffer required for 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);
Parameters :
buf: Buffers that need to be read
Count: Maximum read byte count

return Value: the number of bytes read successfully returned, error 1 and set errno, if the end of the file was reached before the read, this time read returns 0 .   

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


2, fopen library functions
header file : <stdio.h
function prototype : file * fopen (const char * path, const char * mode);
Path string contains the file path and filename to open, and the parameter mode string represents the flow pattern.
Mode has the following morphological strings:
"W" or "WB"     write to open the file and truncate the file length to zero.
"a" or "AB"       write to open the file, append the new content to the end of the file.
"r+" or "rb+" or "r+b"       open (read and write)
"w+" or "wb+" or "w+b"   open in an updated manner and truncate the file length to zero.
"A +" or "ab+" or "a+b"     are opened in an updated way, and 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. (does not differentiate between binaries and text files under Linux)
return value : When a file is opened successfully, a pointer to the stream is returned. Returns null if the file fails to open, and the error code exists in errno.

--------------------------------------------------------------------------------------------------------------- ----
freadis a function. Reads data from a file stream, reading up to count elements, each element of size byte, if the call succeeds in returning the number of elements actually read to, if it is unsuccessful or is read to the end of the file returns 0.
function Prototypes:size_t fread (void *buffer, size_t size, size_t count, FILE *stream);
Parameters:
Buffer: The memory address used to receive data
size: The number of bytes to read and write, in bytes
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. If the return value is not the same as count, you might end up with an error, get an error message from Ferror and feof, or detect whether the end of the file has been reached.
--------------------------------------------------------------------------------------------------------------- ----
fwrite:Write a data block to a file
function Prototypes:size_t fwrite (const void* buffer, size_t size, size_t count, file* stream);
Parameters:
Buffer: is a pointer to the fwrite, is to obtain the address of the data;
size: The number of single bytes 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 all the data in the file stream immediately.
function Prototypes:int fflush (FILE *stream);
--------------------------------------------------------------------------------------------------------------- ----
fseek: The file stream function that is called by the Lseek system. It specifies the location for the next read and write operation in the file stream.
function Prototypes: int fseek (FILE *stream, long offset, int fromwhere);
parameter StreamAs a file pointer
parameter OffsetAs an offset, a positive number represents a positive offset, negative numbers indicate a negative offset
parameter 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 Location
Seek_end: End of File
Where Seek_set,seek_cur and Seek_end are 0, 1, and 2 in turn.
return value: If the execution succeeds, the stream will point to the position with Fromwhere as the base offset (pointer offset) byte, and the function returns 0. If execution fails (for example, offset exceeds the file size), the position pointed to by the stream is not changed, and the function returns a value other than 0.

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

The following is the next open file for Linux and displays 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);
Parameters :
FileName: The file name to open
mode: The file opens with the same mode as in fopen (R/W)
Stream: A file pointer, typically using a standard stream file (Stdin/stdout/stderr)
return value : Returns the pointer to the stream if successful, otherwise null.
action: a function that redirects the input and output stream, redirecting the standard input, output, error, or file stream in the stream to the contents of the filename file. The redirection output under Linux is easy to use./Program name >test (>>test append), Input output redirection under Windows can use Freopen.

How to use: 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 as read-only 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.