Processing of random access files in C ++

Source: Internet
Author: User

Like many C ++ programs, some prefer to use the original C language to handle problems. If you happen to be one of these people, you should take a look at this article.

Basic file operations include:

◆ Fopen-open the file and specify the method (read/write) and type (Binary/text) of the file)

◆ Fclose -- close opened files

◆ Fread -- read files

◆ Fwrite -- write an object

◆ Fseek/fsetpos -- transfers the file indicator to a certain place in the file

◆ Ftell/fgetpos -- tell you where the file indicator is located

There are two basic types of files: Text and binary. Among the two, the binary type is usually easier to solve. Because Random Access processing is not commonly used in the text, we will focus on the processing of binary files in this article. The first four operations listed above can be used for text files and random access files. The following two items are only used for random access.

Random Access means that we can switch between any part of the file and read and write data from it without having to read the entire file.

Binary files

A binary is a file of any length. It stores byte values ranging from 0 to 0xff (0 to 255. These bytes do not make any sense in the binary file. In a text file, if the value is 13, the carriage return is returned. If the value is 10, the line feed is returned. If the value is 26, the file ends, the software that reads text files should be able to solve these problems.

In our current terminology, binary files are called bytes streams that contain bytes. Most languages tend to think of them as bytes streams rather than files. The important part is the data stream itself rather than its source. In C, you can consider data in terms of files or data streams. Or, you can think of it as a group leader's array. With Random Access, you can read and write any part of the array.

Example 1:
// Ex1.c: Defines the entry point for the console application.

//

# Include <stdio. h>

# Include <string. h>

# Include <windows. h>

Int FileSuccess (FILE * handle, const char * reason, const char * path ){

OutputDebugString (reason );

OutputDebugString (path );

OutputDebugString ("Result :");

If (handle = 0)

{

OutputDebugString ("Failed ");

Return 0;

}

Else

{

OutputDebugString ("Suceeded ");

Return 1;

}

}

Int main (int argc, char * argv [])

{

Const char * filename = "test.txt ";

Const char * mytext = "Once upon a time there were three bears .";

Int byteswritten = 0;

FILE * ft = fopen (filename, "wb ");

If (FileSuccess (ft, "Opening File:", filename )){

Fwrite (mytext, sizeof (char), strlen (mytext), ft );

Fclose (ft );

}

Printf ("len of mytext = % I", strlen (mytext ));

Return 0;

}

This code shows a simple open binary file to be written. The text character (char *) is written to the file. You usually use text files, but I want to prove that you can write text to binary files.

     // ex1.c

#include < stdio.h>

#include < string.h>

int main(int argc, char * argv[])

{

const char * filename="test.txt";

const char * mytext="Once upon a time there were three bears.";

int byteswritten=0;

FILE * ft= fopen(filename, "wb") ;

if (ft) {

fwrite(mytext,sizeof(char),strlen(mytext), ft) ;

fclose( ft ) ;

}

printf("len of mytext = %i ",strlen(mytext)) ;

return 0;

}

Role of Example 1

In this example, a binary file to be written is opened. The FILE * variable is returned from the fopen () call. If this operation fails, it returns 0.

Fopen() to open the specified file. In this case, test.txt is located in the same folder. Remember, if the file contains a path, all the backspaces must overlap. "C: \ folder \ test.txt" is incorrect. You must use "c: \ folder \ test.txt ".

Because the file style is wb, we are preparing to write binary files. If the file does not exist, the system creates a file. If the file exists, the content in the file will be deleted. If fopen fails to be called, fopen may return 0 because the file is opened, or its name contains invalid characters or an invalid path.

Although you can only check whether ft is 0 (if the value is 0, it is successful), but I still added a FileSuccess () function to ensure this operation. In the window, it displays whether the call is successful and the file name. If you fail, you may need to fix it. Note that there is usually not much output text in Windows for use by the system debugger,

Fwrite (mytext, sizeof (char), strlen (mytext), ft); fwrite () calls to output the specified text. Second, the three parameters are the character size and the length of the string. Both of them are defined by size_t. Note that with a binary file, even if you are writing a (char *) string to the file, it does not have any additional line break characters. If you want these characters, you must explicitly include these characters in the string.

Read/write files

When opening a file, you must specify the method to open it. This means that if you want to attach something to a file, do you want to create a new file and overwrite it? Is it a text file or a binary file? Do you want to read or write a file? In this way, one or more file pattern classifiers are used. File pattern classifiers are separated by letters such as "r", "B", and "w ", "a" and +. "R" indicates opening the file for reading. If the file does not exist or the file cannot be found, this operation will fail. "W" indicates opening a file in the write or empty file mode. If the file exists, the file content will be damaged. "A" indicates opening the file and preparing to write data from the end of the file without deleting the EOF tag before writing new data. If the file does not exist, a file is created first. Adding + to the file model creates the following three new models:

"R +" open the file and wait for reading or writing. "W +" opens the file in the form of an empty file and waits for reading or writing. If the file exists, the file content will be damaged.

"A +" opens the file and waits for reading or adding it. The added operations include removing the EOF mark before the new data is written, and saving the EOF mark after the write is complete, if the file does not exist, create the file first.

The following list shows the combination of character and code including text and binary files. You can usually choose to read or write files from text files, but not both.

For binary files, you can choose to read and write the same file. The list shows the operations that can be performed with the code.

       Mode Type of file Read Write Create Truncate 
r text Read

rb+ binary Read

r+ text Read Write

r+b binary Read Write

rb+ binary Read Write

w text Write Create Truncate

wb binary Write Create Truncate

w+ text Read Write Create Truncate

w+b binary Read Write Create Truncate

wb+ binary Read Write Create Truncate

a text Write Create

ab binary Write Create

a+ text Read Write Create

a+b binary Write Create

ab+ binary Write Create

As far as my experience is concerned, unless you have just created or read the file, you will be lucky to use "w + B.

In other cases, other letters are allowed to exist. For example, Microsoft runs "t" to represent the text mode. "c" is used for recognition, "n" is used for non-approval, "S" is the sequential access optimization buffer, and "R" represents random access, "T" indicates temporary and "D" is used for deletion/temporary storage.

The main reason for using a binary file is flexibility; you can read or write any part of the file. Text files can only be read or written in order. Now with the popularization of SQLite or MySQL databases, the need to use random access in binary files is reduced. In a sense, Random Access to file records is a bit old, but still useful.

Before the popularization of databases, I used various data processing solutions based on random file access. For example, in small files, I use the index/data file mode. This mode includes two files. A data file stores records of different lengths. Another type of file is the index file, which has the same records as the data file. However, in the index file, each record has the same length and is composed of two suitable structures.

struct {??fpos_t pos;??int size; } indexrec; 

The fpos_t type is defined and used by fsetpos () and fgetpos. These are updated versions of fseek and ftell and are more helpful for creating bookmarks. If you are computing a file and need to set the file, you should use fseek (), and ftell () can also give you the current int location.

In practice, fpos_t may be an int, but you should use the fpos_t type. It saves a copy of the current file indicator. This is the attribute of the random access file, which indicates the location of the next read or write. The granularity is one, so you can place it anywhere in the file.

  1. Summary of naming rules for C ++, Java, and C #
  2. Use Lambda functions in C ++ to improve Code Performance
  3. 50 suggestions for C ++ beginners

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.