C ++ operations on files and file operations

Source: Internet
Author: User

C ++ operations on files and file operations

1. Open the disk file

To open a file, you must make necessary preparations before reading and writing the file, including:

(1) contact the file stream object with the specified Disk File resume to allow the file stream to flow to the specified disk file.

(2) Specify the file opening method, such as whether the file is used as an input file or an output file, binary file or ASCII file.

2. Disable Disk Files

After reading and writing an opened disk file, close the file to unassociate the disk file with the file stream.

In this case, you can associate the file stream with other disk files and input and output new files through the file stream.

3. What is a file stream?

A file stream is a data stream that stores an external file as an input/output object. The output file stream is the data from the memory to the external storage file, and the input file stream is the data from the external storage to the memory. Each file stream has a memory buffer corresponding to it.


The following is an example of object operations:

# Include <iostream> # include <fstream> # include <ctime> using namespace std; // select the sort void ran_sort (int a [], int n) {int t; for (int I = 0; I <n-1; I ++) {for (int j = I + 1; j <n; j ++) {if (a [I]> a [j]) {t = a [I]; a [I] = a [j]; a [j] = t ;}}} int main () {int I, a [100]; // write data to the disk file ofstream out_ran; out_ran.open ("F: \ new \ random.txt ", ios: out); // open the file in output mode. If the file does not exist, create a new file. // if the file with this name already exists, clear all the original content if (out_ran.fail () {cout <"failed to open the file! "<Endl; exit (1) ;}srand (unsigned) time (NULL); for (int j = 0; j <100; j ++) {I = rand () % 100; Random Number of 100 [0,100) written to the disk file} out_ran.close (); // close the disk file // The following ifstream in_ran; in_ran.open ("F: \ new \ random.txt", ios: in | ios :: _ Nocreate); if (in_ran.fail () {cout <"failed to open the file! "<Endl; exit (1) ;}for (int I = 0; I <100; I ++) {in_ran> a [I]; // read 100 integers from the disk file, which are sequentially stored in array a} in_ran.close (); // sort the data in array a by ran_sort (a, 100 ); // write the following data to the disk file: The sorted data ofstream out_sort; out_sort.open ("F: \ new \ random_sort.txt", ios: out ); if (out_sort.fail () {cout <"failed to open the file! "<Endl; exit (1) ;}for (int I = 0; I <100; I ++) {out_sort <a [I] <"";} out_sort.close (); system ("pause"); return 0 ;}

Note: After outputting a data to a disk file, you need to output one or more spaces or line breaks to separate data. Otherwise, when reading data from disk files in the future, numbers of multiple integers cannot be separated.





File input and output mode setting value:

Ios: in open a file as input

Ios: out open the file in the output mode (default open mode). If the file already exists, clear all its original content.

Ios: The app opens the file as an output, and the written data is added to the end of the file.

Ios: nocreate open an existing file. If the file does not exist, it fails to be opened. Nocreate indicates that no new file is created.

Ios: in | ios: out


What are the basic operations on files in C language?

I. Reading and writing standard files
1. open the file fopen ()
To open a FILE, you can allocate a FILE structure to the specified FILE in the memory and return the pointer to the user program, in the future, the user program will use this FILE pointer to access the specified FILE. When you use a function to open a function, you must provide the file name, file operation method (read, write, or read/write), if the file name does not exist, it means to create (only for writing files, an error occurred while reading the file), and pointed the file pointer to the beginning of the file. If a file with the same name already exists, delete the file. If no file with the same name exists, create the file and point the file pointer to the beginning of the file.
Fopen (char * filename, char * type );
* Filename is the name pointer of the file to be opened. It is generally expressed by a file name enclosed in double quotation marks. You can also use a path name separated by a double backslash. The * type parameter indicates how to open a file. You can perform the following operations:

Method description
R open, read-only
W open, file pointer to the header, write only
Open a, point to the end of the file, and append it to an existing file
Rb open a binary file, read-only
Wb open a binary file and write only
AB open a binary file and append it.
R + open an existing file in read/write mode
W + creates a new text file in read/write mode
A + open a file and append it in read/write mode
Rb + opens a binary file in read/write mode
Wb + creates a new binary file in read/write mode
AB + opens a binary file in read/write mode for appending

When fopen is used (0 successfully opens a FILE, this function returns a FILE pointer. If the FILE fails to be opened, a NULL pointer is returned. To open the test file, write:

FILE * fp;
If (fp = fopen (test, w) = NULL)
{
Printf (File cannot be opened \ n );
Exit ();
}
Else
Printf (File opened for writing \ n );
......
Fclose (fp );

The DOS operating system has a limit on the number of files opened at the same time. The default value is 5. You can change this setting by modifying the CONFIG. SYS file.

2. close the file function fclose ()
After the file operation is complete, you must use the fclose () function to close it. This is because when you write an opened file, if the File Buffer space is filled with unwritten content, these contents are not written to open files and are lost. Only when the opened file is closed can the content in the File Buffer be written to the file to complete the file. Once the FILE is closed, the FILE structure corresponding to the FILE will be released, so that the closed FILE will be protected, because the access to the FILE will not be performed. When the file is closed, the buffer of the file is released.
Int fclose (FILE * stream );
It indicates that the function will close the FILE corresponding to the FILE pointer and return an integer. If the file is successfully closed, a 0 value is returned; otherwise, a non-0 value is returned. Perform the test using the following methods:

If (fclose (fp )! = 0)
{
Printf (File cannot be closed \ n );
Exit (1 );
}
Else
Printf (File is now closed \ n );

When you open multiple files and close them at the same time, you can use the fcloseall () function to close all files opened in the program.
Int fcloseall ();
This function will close all opened files, write the content not fully loaded in the file buffer to the corresponding files, release these buffers, and return the number of closed files. If four files are closed, run the following command:
N = fcloseall ();
N should be 4.
3. file read/write
(1). read and write the text... the remaining full text>

C language operations on files

Use this password to create a file
System ("mkdir D: \ abc \ def ");
Mkdir -- windows, unix, and so on. The path is similar:
System ("mkdir/usr/wang/app/src ");

Create FILE fopen
I wrote specific code for you.

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

Int main (){

System ("mkdir D :\\ abc \ def"); // a folder named abc under drive D is created in its directory at the same time.
FILE * f;
If (f = fopen ("D :\\ abc \ 1.txt"," wb ") = NULL) {create a 1.txt file under the D: \ abcfile directory
Printf ("\ nopen file error ");
Getchar ();
Exit (1 );
}
Fputs ("test", f);/* write test Data */
Fclose (f );
Return 0;
}

Fopen requires # include <stdio. h>
Sysytem needs # include <stdlib. h>

Hope to help you!

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.