Read/write "C + +" files

Source: Internet
Author: User

C Language:

1. binary file Write

#include <stdio.h>void main () {int ar[10] = {12,23,34,45,56,67,78,89,90,100}; FILE *FP = NULL;                                  File pointer fp = fopen ("Text2.txt", "w");                      Open file while (!FP)                                        //Open failed {cout<< "Open file fail!" <<endl;return;} Fwrite (ar,sizeof (int), 10,FP);                    Write binary file fclose (FP);                                      Close

2. binary file read

<span style= "FONT-SIZE:18PX;" > #include <stdio.h>void main () {int ar[10]; FILE *FP = NULL;                                File pointer fp = fopen ("Text2.txt", "R");                    Open file while (!FP)                                      //Open failed {cout<< "Open file fail!" <<endl;return;} Fread (ar,sizeof (int), 10,FP);                    Binary Read file fclose (FP);                                     Close}</span>

3. File Write

<span style= "FONT-SIZE:18PX;" > #include <stdio.h>void main () {int ar[10] = {12,23,34,45,56,67,78,89,90,100}; FILE *FP = NULL;                                File pointer fp = fopen ("Text3.txt", "w");                    Open file while (!FP)                                      //Open failed {cout<< "Open file fail!" <<endl;return;} for (int i = 0;i < 10;++i)                       //write Data {fprintf (FP, "%5d", Ar[i]);} Fclose (FP);                                     Close File}</span>

4. File reading

<span style= "FONT-SIZE:18PX;" > #include <stdio.h>void main () {int ar[10]; FILE *FP = NULL;                              File pointer fp = fopen ("Text3.txt", "R");                  Open file while (!FP)                                    //Open failed {cout<< "Open file fail!" <<endl;return;} for (int i = 0;i < 10;++i)                     //read out data {fscanf (FP, "%d", &ar[i]);} Fclose (FP);                                   Close}</span>

C + +:

C + + provides formatted input and output in class iOS. These formats are available for all text mode input and output streams. The format control is defined as an unnamed enum type that is public:

enum{skipws=0x0001,//skip whitespace characters in input
left=0x0002, //output left justified
right=0x0004, //Output right-justified
internal=0x0008, //fill in after output symbol or numbering string
dec=0x0010, //data is processed in decimal when input/output
oct=0x0020, //data is processed in octal at input and output
hex=0x0040, //hexadecimal processing of data at input and output
showbase=0x0080, //At output with characters representing the numbering base

showpoint=0x0100,//output floating point number, must take the decimal point

uppercase=0x0200,//output hex, in uppercase
showpos=0x0400, //Output positive, plus "+" number
scientific=0x0800, //scientific number mode output floating-point numbers
fixed=0x1000, //fixed-number mode output real numbers
unitbuf=0x2000, //after inserting, flush stream immediately
stdio=0x4000} //After inserting, refresh stdout and stderr immediately

Each enumerator in this enumeration description actually corresponds to a bit in the two-byte data (16-bit), so you can use several format controls at the same time, as long as the corresponding position 1, so that both convenient and save memory. Use or "|" When taking multiple controls operator to synthesize, to form a long integer number, in iOS:
Protected
Long x_flags;

Three input and output stream format control flags are also set in the class iOS:
Protected
int x_precision; Flag floating point precision, default is 6 bits
int x_width; The output field is wide, the default domain width is 0,
Resetting the field width is only valid for the first output entry thereafter, and is unrestricted if the domain is not wide enough
Char X_fill; Characters that are filled when the flag field is wide


Standard device input is the least secure, note the following points to avoid errors:
1. Cin is a buffered stream. The data entered by the keyboard is saved in the buffer and is taken from the buffer when it is to be extracted. If the input too much, will stay there slowly use, if the input is wrong, you must change before the carriage return, if the ENTER key is not saved. New data is required only after the data in the input buffer has been taken out. Can not be flushed to clear the buffer, so can not be wrong, also can not lose more!

2. The input data type must be the same as the data type to be extracted, otherwise an error occurs. The error simply corresponds to the position bit (1) in the state of the stream's status word (enum type io_state), and the program continues. Therefore, in order to improve the robustness, it is necessary to add the judgment of State in the programming.
3. Spaces and carriage returns can be used as a separator between data, so multiple data can be entered on one line or branch. However, if it is a character type and a string, the space (ASCII code 32) cannot be entered with CIN, and there are no spaces in the string. The carriage return cannot be read in either.


Opening and closing of files

The steps for using the file are as follows:
1. Describes a file stream object, which is also referred to as an internal file:
Ifstream ifile;//only input with
Ofstream ofile;//only output with
FStream iofile;//both input and output

2. Open a disk file using the file stream object's member function. This establishes a connection between the file stream object and the disk file name. The file stream describes the member functions of the three open files.
void Ifstream::open (const char*,int =ios::in,
Int=filebuf::openprot);
void Ofstream::open (const char *,int=ios::out,
Int=filebuf::opernprot);
void Fstream::open (const char*,int,
Int=filebuf::openprot);
The first parameter is the file name of the disk to open. The second argument is open, with input (in), output (out), and so on, defined as an enumeration type in the iOS base class. The third parameter is the method of protecting the specified open file, which is generally the default. So the second step can be as follows:
Iofile.open ("MyFile.txt", ios::in|ios::out);

Three file stream classes overload a constructor with default parameters, as with the Open function:
Ifstream::ifstream (const Char*,int=ios::in,int=filebuf::openprot);
Ofstream::ofstream (const char*,int=ios::out,
Int=filebuf::openprot);
Fstream::fstream (const Char*,int,
Int=filebuf::operprot);
So 1, 22 steps can be synthesized:
FStream iofile ("MyFile.txt", ios::in|ios::out);

Open the file should also determine whether the success, if successful, the file stream object value is not 0 value, the unsuccessful is 0 (NULL), the file stream object value is physically referred to its address.
So open a file complete program for:
FStream iofile ("MyFile.txt", ios::in|ios::out);
if (!iofile) {
cout<< "Cannot open file:" << "Myfile,txt" <<endl;
Exit (1); }//Failed to return the operating system

3. Use the extract and insert operators to read and write files, or use member functions to read and write, as discussed in the next section.
4. Close the file. Three file stream classes each have a member function that closes a file
void Ifstream::close ();
void Ofstream::close ();
void Fstream::close ();
Very convenient to use, such as:
Iofile.close ();

When the file is closed, the system writes the data in the file buffer associated with the file to a file, guarantees the file's integrity, reclaims the memory space associated with the file, and can be redistributed, disconnecting the disk file name from the file stream object, and preventing erroneous operations from modifying the disk file. If you have to reopen the file operation again.
Closing a file does not cancel the file stream object, which in turn can be associated with other disk files. The file stream object is revoked by the destructor at the end of the program, or at the end of its lifetime. It also frees the internally allocated reserved buffers.

The file opening method is defined in the iOS class, and the public enumeration member:
Enum open_mode{
IN=0X01,//Open file for input operation (read from file), file pointer in file header
OUT=0X02,/* Open file for writing to file. If the file does not exist, it is established, but the specified
The record must exist or the file creation fails. If the file exists, it is not set
App,ate,in the file is emptied */
ate=0x04,
Open file for input/output, file pointer at end of file, but new data can be written anywhere
app=0x08,//Open file for output, but add from tail, new data can only be added at trailer
trunce=0x10,//Open the file and empty it to create a new file
nocreate=0x20,//Opens if file exists, does not exist and does not create a new file
noreplace=0x40,
Created if the file does not exist, if the file exists, can only be set to ate and app mode
BINARY=0X80}; Open file in binary mode using the same method as the format control

1. File Write

#include <iostream> #include <fstream>using namespace std;void main () {int ar[10] = { 12,23,34,45,56,67,78,89,90,100};     The content of the given write file ofstream ofile;                                    File output stream Ofile.open ("Text1.txt", ios::out);                  Open file while (!ofile)                                      //Open Error {cout<< "Open File fail!" <<endl;return;} for (int i = 0;i < 10;++i)                          //Open {ofile<<ar[i]<< "";} Ofile.close ();                                     Close File}


2. File reading

#include <iostream> #include <fstream>using namespace std;void main () {int Ar[10];ifstream ifile;                                  File input stream Ifile.open ("Text1.txt", ios::in);                 Open file while (!ifile)                                    //Open failed {cout<< "Open file fail!" <<endl;return;} for (int i = 0;i < 10;++i)                        //Read file {ifile>>ar[i];} Ifile.close ();                                   Close File}


3. Copying files

#include <iostream> #include <fstream>using namespace std;void main () {Ifstream sfile ("e:\\vc++\\text1.c") ; Ofstream Dfile ("e:\\t.c");                Can only create a file, cannot establish a subdirectory, such as the path does not exist and fails char ch;if (!sfile) {cout<< "Open Source File fail!" <<endl;return;} if (!dfile) {cout<< "Open Target File fail!" <<endl;return;} SFILE.UNSETF (IOS::SKIPWS);          The key! To skip the blank control position 0, that is, do not skip the blank, otherwise the blank is all not copied while (Sfile>>ch) {dfile<<ch;} Sfile.close ();                      If you do not have these two close functions, the destructor can also close dfile.close ();}

4. Copy text files by line

#include <iostream> #include <fstream>using namespace std;void main () {char Filename[256],buf[100];fstream sfile,dfile;cout<< "path name of the input source file:" <<endl;cin>>filename;sfile.open (filename,ios::in);                  Open an existing file while (!sfile) {cout<< "The original file cannot be found, re-enter the pathname:" <<endl;cin>>filename;sfile.open (filename, Ios::in);} cout<< "Input destination file path name:" <<endl;cin>>filename;                                 Can only create a file, cannot establish a subdirectory, such as the path does not exist the failure Dfile.open (filename,ios::out); if (!dfile) {cout<< "target file creation failed" <<endl;return;} while (Sfile.getline (buf,100))//copy by row {if (Sfile.gcount () <100)//due to carriage return not sent to {dfile<<buf<< ' \ n ';} else//Line is greater than 99 characters, not yet read to carriage return newline character, so do not add ' \ n ' {dfile<<buf;}} Sfile.close ();d file.close ();}

Please point out the insufficient place ~ Thank you, I will try to correct.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Read/write "C + +" files

Related Article

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.