C++ 11 深度学习(九)C++文件IO
生活随笔
收集整理的這篇文章主要介紹了
C++ 11 深度学习(九)C++文件IO
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1.將數據寫入文件
#include <iostream> #include <fstream> using namespace std;int main() {ofstream p1;p1.open("outfile.txt");p1 << "向文件寫入信息" << endl;p1.close();return 0; }2.將數據從文件中讀出
#include <iostream> #include <fstream> using namespace std;int main() {char p[40];ifstream p1;p1.open("outfile.txt");p1 >> p;cout << p << endl;p1.close();return 0; }3.格式化輸出讀取一行
#include <iostream> #include <fstream> using namespace std;int main() {char p[40];ifstream p1;p1.open("outfile.txt");if (p1.fail()){return 0;}while (!p1.eof()){//讀取一行,以#為分隔p1.getline(p, 40, '#');cout << p << endl;}p1.close();return 0; }4.字符操作
? ?instream.get( )獲取一個字符
? ?outstream.put( )寫入一個字符
5.文件打開模式
??
6.流狀態位
clear函數作用是所有標志位置為0.
7.二進制讀寫
8.將任意類型數據寫入文件
?把數據需要轉換為字節序列,即字節流;可以使用??reinterpret_cast(address)?
1.寫入操作
#include <iostream> #include <armadillo> #include <fstream> using namespace std; using namespace arma;int main() {fstream binaryio;binaryio.open("city.dat", ios::out | ios::binary);int value = 199;binaryio.write(reinterpret_cast<char*>(&value), sizeof(value));binaryio.close();cout << "Done" << endl;return 0; }2.讀取操作
#include <iostream> #include <armadillo> #include <fstream> using namespace std; using namespace arma;int main() {fstream binaryio;binaryio.open("city.dat", ios::in | ios::binary);int value;binaryio.read(reinterpret_cast<char*>(&value), sizeof(value));binaryio.close();cout << value << endl;return 0; }3.二進制寫入與讀取數組
#include <iostream> #include <armadillo> #include <fstream> using namespace std; using namespace arma;#define SIZE 5 int main() {//二進制寫入數組double array[SIZE] = { 3.4 , 1.3 , 2.5 , 5.66 , 6.9 };fstream binaryio;binaryio.open("city.dat", ios::out | ios::binary);binaryio.write(reinterpret_cast<char*>(&array), sizeof(array));binaryio.close();//二進制讀取數組double result[SIZE];binaryio.open("city.dat", ios::in | ios::binary);binaryio.read(reinterpret_cast<char*>(&result), sizeof(array));binaryio.close();for (int i = 0; i < SIZE; i++){cout << result[i] << endl;}return 0; }4.當將對象存儲到文件中的時候,只存儲數據域,而不存儲函數域。
5.隨機訪問文件方法
總結
以上是生活随笔為你收集整理的C++ 11 深度学习(九)C++文件IO的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: vivo电脑多少钱(vivo电脑多少钱一
- 下一篇: 黑板灯设置(黑板灯位置安装参考图)