How to read and write this file

Source: Internet
Author: User
Tags relative
Requirements:
Learn how to read and write text files
Learn how to read and write binary files C + + file stream:
FStream//File stream
Ifstream//input file stream
Ofstream//output file stream C + + code replication codes
Create a text file and write information
//output information to a file as you would on the screen
#include <iomanip.h>
#include <fstream.h>
void Main ()
{
  ofstream F1 ("D:\\me.txt");           Open file for write, if the file does not exist, create it
  if (!F1) return;                 Open file failed to end run
  f1<<setw << "Name:" << "East" <<endl;     Use the Insert operator to write the contents of a file
  f1<<setw << home Address: << Zhengzhou, Henan <<endl;
  F1.close ();                   Close File
}
After running, open the file D:\me.txt, which reads as follows:
Name: William Oriental
Home Address: Henan Zhengzhou file operation:
Open File
Filename
Note that the slash in the path name is double-written, such as:
"D:\\myfiles\\readme.txt"
File Open With options:
Ios::in = 0x01,//read, File not present (ifstream default open mode)
Ios::out = 0x02,//write, the file does not exist, and if the file already exists, empty the original content (ofstream default open mode)
Ios::ate = 0x04,//When the file is opened, the pointer is at the end of the file. Can change the position of the pointer, often combined with in and out
Ios::app = 0x08,//write, the file does not exist, and if the file already exists, then writes the new content after the original file content, the pointer position is always at the last
Ios::trunc = 0x10,//Truncate the file length to 0 (default) before reading and writing
Ios::nocreate = 0x20,//The file does not exist and generates an error, often combined with in or app
Ios::noreplace = 0x40,//file generated error when present, common and out combined use
Ios::binary = 0x80//binary format file
File Protection options:
Filebuf::openprot; The default compatible sharing method
Filebuf::sh_none; Exclusive, not shared
Filebuf::sh_read; Read share
Filebuf::sh_write; Write sharing
Ways to open a file
Specify the file name and open mode when calling the constructor
Ifstream f ("D:\\12.txt", ios::nocreate); The default is to open the file as Ios::in, and the operation fails when the file does not exist
Ofstream f ("D:\\12.txt"); Open files by default in Ios::out mode
FStream f ("D:\\12.dat", ios::in|ios::out|ios::binary); Open a binary file as read-write
Using the Open member function
FStream F;
F.open ("D:\\12.txt", ios::out); Use the Open function when working with multiple files using the same object
Check if Open successfully
Success:
if (f) {...} The FStream object is not available for Ifstream, Ofstream objects.
if (F.good ()) {...}
Failed:
if (!f) {...} ! Operator is overloaded
if (F.fail ()) {...}
Read and write operations
Using the <<,>> operator
Only text files can be read and written, and used in binary files may produce errors.
Use function members get, put, read, write, and so on
The function that is often used in conjunction with Read is Gcount (), which is used to obtain the actual number of bytes read.
Read and write binary file considerations
Ios::binary must be specified in open mode, otherwise read-write error
Read and write with Read\write, but not with the insert, extract operator, or an error occurs.
Use the EOF () function to detect if a file is read-end, using Gcount () to get the actual number of bytes read
Close File
Use the member function close, such as:
F.close ();
Using destructors
The end of the object lifetime checks to see if the file is closed and closes the file without closing it.
Random Read and write files
You can read and write to a file at the specified location by moving the file read and write pointers.
SEEKG (absolute position); Absolute move,//input stream operation
SEEKG (relative position, reference position); Relative operation
Tellg (); Returns the current pointer position
SEEKP (absolute position); Absolute movement,//output stream operation
SEEKP (relative position, reference position); Relative operation
TELLP (); Returns the current pointer position
Reference location:
Ios::beg = 0//relative to file header
Ios::cur = 1//relative to the current position
Ios::end = 2//relative to end of file
Examples of reading and writing text files
C + + code replication codes
To be able to correctly read the data written to the file, it is best to have the separation between the data
#include <fstream.h>
void Main ()
{
  fstream f ("D:\\try.txt", iOS :: Out);
  f<<1234<< ' <<3.14<< ' A ' << ' how is you '; Write Data
  f.close ();
  F.open ("D:\\try.txt", ios::in);
  int i;
  Double D;
  char c;
  Char s[20];
  f>>i>>d>>c;               Read Data
  f.getline (s,20);
  cout<<i<<endl;             Show each data
  cout<<d<<endl;
  cout<<c<<endl;
  cout<<s<<endl;
  F.close ();
}
Operation Result:
1234
3.14
A
How is You
Press any key to continue
Display the contents of a text file
Use Get () to read one character at a time--------------------------------scheme one
C + + code replication codes
#include <fstream.h>
void Main ()
{
  ifstream fin ("d:\\ introduction. txt", ios::nocreate);
  if (!fin) {
    cout<< "File open error!\n";
    return;
  }
  char c;
  while ((C=fin.get ())!=eof) cout<<c;    Note the judgment of the end condition
  fin.close ();
}

Use Get (char *,int n,char delim= ' \ n ') to read multiple characters at once----scenario two
Clever use of text files without the character ' \ S ' Feature for reading
C + + code replication codes
#include <fstream.h>
void Main ()
{
  ifstream fin ("d:\\ introduction. txt", ios::nocreate);
  if (!fin) {
    cout<< "File open error!\n";
    return;
  }
  Char c[80];
  while (Fin.get (c,80, '!=null ') cout<<c; Note the judgment of the end condition
  fin.close ();
}
Using read (char *,int N) reading a file---------------------------scenario three
C + + code replication codes
#include <fstream.h>
void Main ()
{
  ifstream fin ("d:\\ introduction. txt", ios::nocreate);
  if (!fin) {
    cout<< "File open error!\n";
    return;
  }
  Char c[80];
  while (!fin.eof ())            //Determine if the file read-end
  {
    fin.read (c,80);
    Cout.write (C,fin.gcount ());
  }
  Fin.close ();
}
Copy files
Binary File Operation example
C + + code replication codes
#include <fstream.h>
void Main ()
{
  ifstream fin ("C:\\1.exe", ios::nocreate|ios::binary);
  if (!fin) {
    cout<< "File open error!\n";
    return;
  }
  Ofstream fout ("C:\\2.exe", ios::binary);
  Char c[1024];
  while (!fin.eof ())
  {
    fin.read (c,1024);
    Fout.write (C,fin.gcount ());
  }
  Fin.close ();
  Fout.close ();
  cout<< "Copy over!\n";
}

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.