#include #include using namespace std; int main () { string fileName; string line, buff; // 定义文件流 // fstream: 读写 // ofstream: out写 // ifstream: in读 fstream fs; // string fileName = "/Users/clarklin/Downloads/20221123/test.txt"; cout << "Input full path of file to read:" << endl; cin >> fileName; fs.open(fileName, ios::in); // 如果文件打不开? if (!fs) { cout << "Cannot open file.\n"; return 1; } else { // 逐行读取 cout << "----- Read by line -----" << endl; while (getline(fs, line)) { // 在while的条件中已经读取了行,输出到控制台 cout << line << endl; } // 将文件指针移动回文件的开头,偏移0L(Long) // 文件指针可用的位置包括ios::beg, ios::cur, ios::end fs.clear(); fs.seekg(0L, ios::beg); // 重新逐行读取 cout << "----- Re-Read by line -----" << endl; while (getline(fs, line)) { // 在while的条件中已经读取了行,输出到控制台 cout << line << endl; } fs.close(); } // 再次打开 fs.open(fileName, ios::in); // 如果文件打不开? if (!fs) { cout << "Cannot open file.\n"; return 1; } else { cout << "----- Read by string -----" << endl; // 逐词读取,忽略空格 while (fs >> line) { // 在while的条件中已经读取了字符,作为单独一行,输出到控制台 cout << line << endl; } fs.close(); } cout << "Input full path of file to write:" << endl; cin >> fileName; // ios::app - 追加 // ios::ate - 移动到文件末 // ios::out - 写(默认清空) // ios::trunc - 清空 fs.open(fileName, ios::out | ios::app); // 如果文件打不开 if (!fs) { cout << "Cannot open file.\n"; return 1; } else { cout << "----- Input string to append -----" << endl; // 等待用户输入新的字符串(不包含空格) cin >> line; // 写入新的字符串(作为新行) fs << line << endl; cout << "----- Input line to append -----" << endl; // 这个buff用来接收之前cin收到的回车 // 否则下一条getline的命令会获取前面一条cin的回车,不会接受新的行 getline(cin, buff); // 等待用户输入新的行 getline(cin, line); // 写入新的行 fs << line << endl; fs.close(); } return 0; }