c++ read and write TXT file collation method
- 2020-06-07 04:57:54
- OfStack
As shown below:
#include "stdafx.h"
#include <iostream>
// Include both read and write <fstream> The header file
#include <fstream>
#include <iomanip>
using namespace std;
int main()
{
//ifstream Flow from file to memory ifstream Represents a file input stream, meaning a file read operation
ifstream myfile("c://a.txt");
//ofstream Flow from memory to files ofstream Represents a file output stream, meaning a write file operation
ofstream outfile("c://b.txt");
fstream fin1("file1.txt", ios::in);
/*********************************************************************************************************/
// Examples of reading files
// If the file does not exist (in visual stdio 2017 In the environment, the file exists .vcxproj In the file folder)
if (!fin1) {
// tried 1 Next, use cout That's fine. Now I don't understand why cerr Why is the standard library defined cerr This object
cerr << " Read failure " << endl;
system("pause");
return -1;
}
else {
cout << " Read the success " << endl;
// Note that the document is not empty
if (outfile.is_open())
{
char linestring[100];
//memset Function in the socket Is used to empty arrays . Such as : The prototype is memset(buffer, 0, sizeof(buffer))
//memset(linestring, 0, 100);
//file.good() An error occurs while a file is being read or written, or the file is returned only after it has been read false;
//eof At the end of the read 1 After the data, it's still zero False ", when trying to read again 1 Of the data,
// Because I found no data to read, I knew I was at the end, and then I changed the flag. eof into True
if (myfile.good() && !myfile.eof()) {
// read info.txt the 1 Ok, deposit linestring
myfile.getline(linestring, 100);
// The character 1 a 1 A processing until encountered '/0' So far,
for (int i = 0; linestring[i] != 0; i++)
// through ASCII Code to ensure that the input character is a character
if (linestring[i] >= 65 && linestring[i] <= 90 || linestring[i] >= 97 && linestring[i] <= 122) {
// Saves alphabetic characters to a disk file
outfile.put(linestring[i]);
cout << linestring[i] << "";
}
cout << endl;
outfile.close();
}
}
}
/*********************************************************************************************************/
// Examples of writing files
char ch;
// Open the file as input
ifstream infile("f1.dat", ios::in);
// If the file doesn't exist
if (!infile) {
cerr << "open error!" << endl;
exit(1);
}
// Define output stream f3.dat file
ofstream outfile("f3.dat");
if (!outfile) {
cerr << "open error!" << endl;
exit(1);
}
// When the read character is successful
while (infile.get(ch)) {
if (ch <= 122 && ch >= 97)
ch = ch - 32;
outfile.put(ch);
cout << ch;
}
cout << endl;
infile.close();
outfile.close();
system("pause");
return 0;
}