如下所示:
#include "stdafx.h"#include <iostream> //無論讀寫都要包含<fstream>頭文件#include <fstream> #include <iomanip> using namespace std; int main(){ //ifstream從文件流向內存的ifstream表示文件輸入流,意味著文件讀操作 ifstream myfile("c://a.txt"); //ofstream從內存流向文件的ofstream表示文件輸出流,意味著寫文件操作 ofstream outfile("c://b.txt"); fstream fin1("file1.txt", ios::in); /*********************************************************************************************************/ //讀文件的例子 //如果文件不存在(在visual stdio 2017環境下,文件存在了有.vcxproj文件的那個文件夾里面) if (!fin1) { //試了一下,用cout也可以,現在我還不明白為什么用cerr,為什么標準庫要定義cerr這個對象 cerr << "讀取失敗" << endl; system("pause"); return -1; } else { cout << "讀取成功" << endl; //說明文件非空 if (outfile.is_open()) { char linestring[100]; //memset函數在socket中多用于清空數組.如:原型是memset(buffer, 0, sizeof(buffer)) //memset(linestring, 0, 100); //file.good()是在文件讀取或者寫的過程中出現錯誤,或者讀到文件最后繼續讀才會返回false; //eof在讀取完最后一個數據后,仍是False,當再次試圖讀一個數據時, //由于發現沒數據可讀了,才知道到末尾了,此時才修改標志,eof變為True if (myfile.good() && !myfile.eof()) { // 讀取info.txt的一行,存入linestring myfile.getline(linestring, 100); //對字符一個一個的處理,直到遇到'/0'為止 for (int i = 0; linestring[i] != 0; i++) //通過ASCII碼,保證輸入的字符是字符 if (linestring[i] >= 65 && linestring[i] <= 90 || linestring[i] >= 97 && linestring[i] <= 122) { //將字母字符存入磁盤文件 outfile.put(linestring[i]); cout << linestring[i] << ""; } cout << endl; outfile.close(); } } } /*********************************************************************************************************/ //寫文件的例子 char ch; //以輸入的方式打開文件 ifstream infile("f1.dat", ios::in); //如果文件不存在 if (!infile) { cerr << "open error!" << endl; exit(1); } //定義輸出流f3.dat文件 ofstream outfile("f3.dat"); if (!outfile) { cerr << "open error!" << endl; exit(1); } //當讀取字符成功時 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;}
以上這篇c++讀取和寫入TXT文件的整理方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持VEVB武林網。
新聞熱點
疑難解答