Randomaccessfile class in Linux

Source: Internet
Author: User

Randomaccessfile class in Linux

Note: The following is basically nonsense (but you don't want to delete it). Please read this page and change a page or blog to browse it. Thank you ----- fliggy flying

In the following situations:
1. When reading and writing files larger than the memory size
2. If you do not want to load the entire file, you need to read and write a part of the file.

The Java randomaccessfile may be very practical and convenient.
Such instances support reading and writing random access files. Random access to files is similar to a large byte array stored in the file system. There is a cursor or index pointing to the hidden array, which is called a file pointer. The input operation reads bytes from the file pointer and advances the file pointer as the bytes are read. If a random access file is created in read/write mode, the output operation is also available. The output operation starts writing bytes from the file pointer and advances the file pointer as the bytes are written. The output operation after the current end of the hidden array causes the array to expand. The file pointer can be read using the getfilepointer method and set using the seek method.

If you want to implement this function in Linux, you can use MMAP (System Call)

Next we will first introduce the use of MMAP and write a simple C ++ class of randomaccessfile implemented by MMAP, to meet the needs of using C ++ to solve the two situations mentioned at the beginning.

MMAP Introduction
MMAP example
C ++ Implementation of randomaccessfile

######################################## ######################################## #######
MMAP Introduction
MMAP definition:
Void * MMAP (void * ADDR, size_t Len, int Prot, int flags, int FD, off_t offset );

Function Parameter Parsing:
The FD parameter is the description of the file to be mapped to the process space, which is generally returned by open.

Len is the number of bytes mapped to the address space of the calling process. It starts from the offset byte at the beginning of the mapped file.

The prot parameter specifies the access permission for the shared memory. The following values can be obtained: prot_read (readable), prot_write (writable), prot_exec (executable), and prot_none (inaccessible ).

Flags are specified by the following common values: map_shared, map_private, and map_fixed. Among them, map_shared and map_private are mandatory, while map_fixed is not recommended.

The offset parameter is generally set to 0, indicating that the ing starts from the file header.

The ADDR parameter specifies that the file should be mapped to the starting address of the process space. Generally, a null pointer is specified. At this time, the task of selecting the starting address is left to the kernel for completion. The Return Value of the function is the address mapped from the last file to the process space. The starting address of a process operation can be the valid address of the value.

######################################## ######################################## ########

MMAP example

# Include <sys/types. h>
# Include <sys/STAT. h>
# Include <fcntl. h>
# Include <stdio. h>
# Include <unistd. h>
# Include <sys/Mman. h>

Int main ()
{

// The Fifth parameter FD of MMAP is obtained by calling open (). If it is-1, opening the file fails.
Int FD;
If (FD = open ("./file", o_rdwr | o_creat, s_irwxu) <0 ){
Printf ("open file wrong! ");
Return 1;
}
 
// The second MMAP parameter Len is obtained by calling fstat (). Normally,-1 should not be returned.
Struct stat file_stat;
If (fstat (FD, & file_stat) <0)
{
Printf ("fstat wrong ");
Return 1;
}

// The first parameter of MMAP is generally null. For details, see the MMAP parameter description above.
// The maximum six parameters of MMAP are the start ing of the file. Generally, 0 indicates the start of the file.
Void * start_fp;
If (start_fp = MMAP (null, file_stat.st_size, prot_read, map_shared, FD, 0) = map_failed)
{
Printf ("MMAP wrong ");
Return 1;
}

//
Snprintf (char *) start_fp, 4, "test ");
Msync (start_fp, file_stat.st_size, ms_async );

// Munmap is similar to the close () function of randomaccessfile in Java, and the file ing function is disabled. The parameter is the void * pointer returned by the ing and the length of the ing file. It can be regarded as the function disabled by the General Io function.
If (munmap (start_fp, file_stat.st_size) <0)
{
Printf ("munmap wrong ");
Return 1;
}
}

General steps for memory ing:

Open the file with an open system call and return the descriptor FD.
Use MMAP to create a memory ing and return the ing first address pointer start.
Perform Various operations on the ing (file), display (printf), and modify (sprintf ).
Use munmap (void * Start, size_t lenght) to disable memory ing.
Use the close system call to close the file FD.

######################################## ####################################
C ++ Implementation of randomaccessfile

The following is a C ++ class implementation of a randomaccessfile of MMAP, which encapsulates some code that looks "unfriendly.
This class only implements the function of reading char, and does not implement the function of reading any type of data similar to Java's randomaccessfile.
Test availability in centos5 and G ++ 4.1.2

# Include <sys/types. h>
# Include <sys/STAT. h>
# Include <fcntl. h>
# Include <stdio. h>
# Include <unistd. h>
# Include <sys/Mman. h>

// 081125 snail Il
Class randomaccessfile
{
Public:
Randomaccessfile (const char * filepath );
~ Randomaccessfile ();
Bool isopen ()
{
Return open_ OK;
}

Long length ()
{
Long size = 0;
If (open_ OK)
{
Size = m_file_stat.st_size;
}
Return size;
}

Void seek (long POS)
{
If (Pos> m_file_stat.st_size)
{
Pos = m_file_stat.st_size;
}
M_offset = Pos;
}

Char readchar ()
{
Return m_file [m_offset];
}

Const char * geterror ()
{
Return m_error;
}

PRIVATE:
Bool open_ OK; // ramomaccessfile is prepared OK
Char * m_file; // If is prepared OK, m_file stands for handle of randomaccessfile
Char * m_error; // If is not prepared OK, m_error stands for error message
Struct stat m_file_stat; // stands for info of file which to be randomaccess
Long m_offset; // offset to start of File
};

Randomaccessfile: randomaccessfile (const char * filepath ):
M_offset (0), open_ OK (true)
{
Int FD;
If (FD = open ("./file", o_rdwr | o_creat, s_irwxu) <0)
{
M_error = "open file wrong! ";
Open_ OK = false ;;
}

If (open_ OK)
{
If (fstat (FD, & m_file_stat) <0)
{
M_error = "fstat wrong ";
Open_ OK = false;
}
}

If (open_ OK)
{
If (m_file = (char *) MMAP (null, m_file_stat.st_size, prot_read,
Map_shared, FD, m_offset) = map_failed)
{
M_error = "MMAP wrong ";
Open_ OK = false;
}
}
}

Randomaccessfile ::~ Randomaccessfile ()
{
If (open_ OK)
{
If (munmap (m_file, m_file_stat.st_size) <0)
{
Printf ("munmap wrong ");
}
}
}

Int main ()
{
Randomaccessfile * RAF = new randomaccessfile ("./file ");
If (RAF-> isopen ())
{
// Printf ("randomaccess file is prepared! /N ");
Printf ("RAF length () --> % d/N", Raf-> length ());
Raf-> seek (0 );
Printf ("% C/N", Raf-> readchar ());
}
Else
{
Printf (RAF-> geterror ());
}

Delete Raf;
}

######################################## #####################################
Refer:
Http://blog.csdn.net/dai_weitao/archive/2007/07/25/1707559.aspx
Http://blog.csdn.net/eroswang/archive/2007/11/30/1908842.aspx
Http://blog.csai.cn/user1/16820/archives/2008/25456.html

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.