C ++ reads and writes text files, counts the number of lines of files, and reads file data to arrays.

Source: Internet
Author: User
Tags readfile

Fstream provides three classes for C ++ to perform file operations. (File Creation, reading, and writing ).
Ifstream -- read from an existing file

Ofstream -- write content to a file

Fstream-open a file for reading and writing

File opening mode:

IOS: In read
IOS: Out write
IOS: The app starts to write at the end of the file.
IOS: Binary binary mode
IOS: nocreate when opening a file, if the file does not exist, no file is created.
IOS: noreplace: When opening a file, if the file does not exist, create the file
IOS: trunc open a file and clear the content
IOS: ate when opening a file, move the location to the end of the file

Usage of file pointer position in C ++:

IOS: Beg File Header
IOS: End file tail
IOS: current location of cur
Example:
File. seekg (0, IOS: Beg); // locate the file pointer to the beginning of the file
File. seekg (0, IOS: End); // locate the file pointer to the end of the file
File. seekg (10, IOS: cur); // move the file pointer from the current position to the end of the file by 10 bytes
File. seekg (-10, IOS: cur); // Let the file pointer move 10 bytes from the current position to the start of the file
File. seekg (10, IOS: Beg); // locate the file pointer to the first 10 bytes from the file

Common error determination methods:

Good () if the file is successfully opened
An error occurred while opening the file in bad ().
EOF () arrives at the end of the file

Instance:

I. Writing files

# Include <iostream>
# Include <fstream>
Using namespace STD;

Void main ()
{
Ofstream in;
In. Open ("com.txt", IOS: trunc); // IOs: trunc indicates to clear the file before opening the file. Because it is written, it is created if the file does not exist.
Int I;
Char A = 'a ';
For (I = 1; I <= 26; I ++) // write 26 numbers and letters into the file.
{
If (I <10)
{
In <"0" <I <"\ t" <A <"\ n ";
A ++;
}
Else
{
In <I <"\ t" <A <"\ n ";
A ++;
}
}
In. Close (); // close the file
}

Open com.txt. The effect is as follows:


Ii. Reading files

The above only writes the text into the file and does not read it.

One of the following methods is to read a file: store each row of the file to a string, and then output a string

# Include <iostream>
# Include <fstream>
Using namespace STD;

Void main ()
{
Char buffer [256];
Fstream out;
Out. Open ("com.txt", IOS: In );
The content of cout <"com.txt" <"is as follows:" <Endl;
While (! Out. EOF ())
{
Out. Getline (buffer, 256, '\ n'); // Getline (char *, Int, char) indicates that the row contains 256 characters or ends when a line break occurs.
Cout <buffer <Endl;
}
Out. Close ();
Cin. Get (); // cin. Get () is used to read the Enter key. If this row is not displayed, the output will disappear as soon as it is generated.
}


Character-by-character file reading:

# Include <iostream>
# Include <fstream>
Using namespace STD;

Void main ()
{
Fstream in;
Char C;
In. Open ("comn.txt", IOS: In );
While (! In. EOF ())
{
In> C;
Cout <C;
}

In. Close ();
Cin. Get ();
}


All characters in the file read by this method are displayed together and will not be split. Here, the letter Z is displayed twice, which is normal because it is output again after the last letter Z in the output file (you can carefully consider the program code ).

Read a row of the file:

# Include <iostream>
# Include <fstream>
# Include <string>
Using namespace STD;

Int countlines (char * filename)
{
Ifstream readfile;
Int n = 0;
String TMP;
Readfile. Open (filename, IOS: In); // IOs: In indicates reading files in read-only mode.
If (readfile. Fail () // failed to open the file: 0 is returned.
{
Return 0;
}
Else // file exists
{
While (Getline (readfile, TMP ))
{
N ++;
}
Return N;
}
Readfile. Close ();
}

String Readline (char * filename, int line)
{
Int lines, I = 0;
String temp;
Fstream file;
File. Open (filename, IOS: In );
Lines = countlines (filename );
If (line <= 0)
{
Return "error 1: the number of rows is incorrect. The value cannot be 0 or a negative number. ";
}
If (file. Fail ())
{
Return "Error 2: The file does not exist. ";
}
If (line> lines)
{
Return "error 3: the number of rows exceeds the file length. ";
}
While (Getline (file, temp) & I <line-1)
{
I ++;
}
File. Close ();
Return temp;
}

Void main ()
{
Int L;
Char filename [256];
Cout <"Enter the file name:" <Endl;
Cin> filename;
Cout <"\ n enter the number of lines to read:" <Endl;
Cin> L;
Cout <Readline (filename, L );
Cin. Get ();
Cin. Get ();
}


Apparently, based on the above program, the entire file content can be read row by row using loops.

3. Number of statistics files

# Include <iostream>
# Include <fstream>
Using namespace STD;

Int countlines (char * filename)
{
Ifstream readfile;
Int n = 0;
Char line [512];
Readfile. Open (filename, IOS: In); // IOs: In indicates reading files in read-only mode.
If (readfile. Fail () // failed to open the file: 0 is returned.
{
Return 0;
}
Else // file exists
{
While (! Readfile. EOF ())
{
Readfile. Getline (line, 512, '\ n ');
N ++;
}
Return N;
}

Readfile. Close ();
}
Void main ()
{
Cout <"the number of lines of comn.txt is:" <countlines ("comn.txt") <Endl;
Cin. Get ();
}

There is no problem with the above program design ideas, but in actual operations, we will find that the number of rows is inconsistent with the actual, because of readfile. getline (line, 512, '\ n'): When a row contains more than 512 characters or returns a carriage return, the number of rows is automatically added to 1. if the line break is in a new row, the returned result is 1 more than the actual one. If the line break is not in a new row, the returned result is consistent with the actual result. You can modify it as follows:

# Include <iostream>
# Include <fstream>
# Include <string>
Using namespace STD;

Int countlines (char * filename)
{
Ifstream readfile;
Int n = 0;
Char line [512];
String temp;
Readfile. Open (filename, IOS: In); // IOs: In indicates reading files in read-only mode.
If (readfile. Fail () // failed to open the file: 0 is returned.
{
Return 0;
}
Else // file exists
{
While (Getline (readfile, temp ))
{
N ++;
}
Return N;
}

Readfile. Close ();
}
Void main ()
{
Cout <"the number of lines of comn.txt is:" <countlines ("comn.txt") <Endl;
Cin. Get ();
}

4. Read File data to an array

# Include <iostream>
# Include <fstream>
# Include <string>
Using namespace STD;

Int countlines (char * filename) // obtain the number of objects
{
Ifstream readfile;
Int n = 0;
String temp;
Readfile. Open (filename, IOS: In); // IOs: In indicates reading files in read-only mode.
If (readfile. Fail () // failed to open the file: 0 is returned.
{
Return 0;
}
Else // The object exists and the number of returned objects
{
While (Getline (readfile, temp ))
{
N ++;
}
Return N;
}
Readfile. Close ();
}

Void main ()
{
Ifstream file;
Int lines;
Char filename [512];
Cout <"enter the name of the file to open:" <Endl;
Cin> filename;
File. Open (filename, IOS: In );
If (file. Fail ())
{
Cout <"the file does not exist." <Endl;
File. Close ();
Cin. Get ();
Cin. Get ();
}
Else // file exists
{
Lines = countlines (filename );
Int * Tc = new int [Lines];
Char * t = new char [Lines];
Int I = 0;
While (! File. EOF () // read data to the array
{
File> TC [I];
File> T [I];
I ++;
}
File. Close (); // close the file
For (I = 0; I <lines; I ++) // outputs the array content
Cout <TC [I] <"\ t" <t [I] <Endl;
Cin. Get ();
Cin. Get ();
}
}

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.