Something about file's read and write (C++)

Purpose: Write down to help me remember and review the knowledge of file’s basic operation in C++

/*There is a problem:
Input: An English text file
Output: A file contains each word’s frequency from the input file, and sort them with the order of ASCII.

Specific description:《数据结构与算法实验实践课程》(P32~33),乔海燕、蒋爱军、高集荣和刘晓铭等编著,清华大学出版社。
*/

一、 Pretend that there is a title

Note that “ifstream” and “ofstream” are difined in header < fstream >

Let’s read word one by one from the first file and then write some data into another file’

Part of the code (some how like a pesudocode) :

#include <fstream>
// each time read a string from the file, until EOF
ifstream in;    
in.open("filename.txt");
if (!in) {          
    cerr << "failed to open" << endl;
    return 1;
}
while (!in.eof) {   // is EOF ?
    in >> word;     // reading, "word" is a string variable
    // ......(operations)
}
in.close();         // don't forget to close the file

// write some data into another file after the operation of the input 
ofstream out;
out.open("filename.txt");
auto it = List.begin();     // "it" is an iterator
while (it != List.end()) {
    out << (*it) << ' ';    // writing
    it++;
}
out.close();

That’s not enough, I’d like to add something about istringstream, which helps me do reading better.
Note that istringstream defined in header < sstream >

#include <fstream>
#include <sstream> 
#include <string> // include getline() function
//-----------------------
while (!in.eof) {
    string line;
    getline(in, line);
    istringstream istr;
    istr.str(line);   // something like turn the string( line ) into stream and stored it into istr
    while (istr >> word) {
        // ......( operatirons)
    }
}

Some URL do help:
std::basic_istringstream::str
std::getline, also mentioned istringstream::str
std::basic_istream::getline
std::basic_fstream


猜你喜欢

转载自blog.csdn.net/ill__world/article/details/78383760