文件的创建与读取 文件的数据添加
生活随笔
收集整理的這篇文章主要介紹了
文件的创建与读取 文件的数据添加
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文件的創建與讀取 ? 文件的數據添加
一:概要
1:首先要站在程序的角度上。
2:文件的創建 即將程序中的數據 寫入到文件當中。
3:文件的讀取 即將一個文件中的信息讀取到程序當中。
二:步驟
1:創建文件流
2:打開文件流
3:往文件中寫入數據
4:關閉文件流
注意:第一步和第二步可以合并為一步 即:ofstream ofile("num.txt",ios::out);
三:上代碼
1:文件的創建:
#include<bits/stdc++.h> using namespace std;//先創建一個文件 然后往文件里寫東西 int main() {int a[5] = { 1,2,3,4,5};//創建文件;ofstream ofile; //ofstream ofile("num.txt",ios::out); //打開文件ofile.open("num.txt",ios::out); if( ofile == NULL){cout << "open fail" << endl;exit(1);}//向文件中寫入數據for( int i = 0; i < 5; i++ ){ofile << a[i] << ' '; } //關閉流文件ofile.close(); }2:文件的讀取(將一個文件中的數據讀入到代碼當中)
#include<bits/stdc++.h> using namespace std;int main() {int b[5];//創建文件 ifstream ifile;//打開文件ifile.open("num.txt", ios::in);//從程序的角度出發 讀入一個文件if( ifile == NULL){cout << "fail" << endl;exit(1); }for( int i = 0; i < 5; i++ ){ifile >> b[i]; }ifile.close();for( int i = 0; i < 5; i++ ){cout << b[i] << ' '; } }3:在一個文件中的內容已有的情況下 存入數據
#include<bits/stdc++.h> using namespace std;int main() {int a[5] = { 1,2,3,4,5};//創建文件;ofstream ofile; //ofstream ofile("num.txt",ios::out); //打開文件ofile.open("num.txt",ios::out); if( ofile == NULL){cout << "open fail" << endl;exit(1);}//向文件中寫入數據for( int i = 0; i < 5; i++ ){ofile << a[i] << ' '; } //關閉流文件ofile.close();int temp = 100;ofile.open("num.txt",ios::app);ofile << ' ' << temp;ofile.close(); }總結
以上是生活随笔為你收集整理的文件的创建与读取 文件的数据添加的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 7-8 哈利·波特的考试 (25 分)(
- 下一篇: 7-14 电话聊天狂人 (25 分)ma