引用標頭檔案 < fstream >
建立流物件
指定檔案及開啟方式
讀寫資料
關閉檔案
ofstream: 寫操作 從記憶體向檔案中輸出資料
ifstream: 讀操作 從檔案中向記憶體中輸入資料
fstream: 讀寫操作
開啟方式
ios::in 為讀檔案而開啟檔案
ios::out 為寫檔案而開啟檔案
ios::ate 初始位置為檔案尾
ios::trunc 如果檔案存在,則先刪除在建立
ios::binary 二進位制方式開啟檔案
多種方式開啟檔案 可用 | 連線 ,如 ios::out | ios::trunc
/*
20190918
c++ 檔案操作
*/#include
using
namespace std;
#include
//標頭檔案
#include
/*開啟方式
ios::in 為讀檔案而開啟檔案
ios::out 為寫檔案而開啟檔案
ios::ate 初始位置為檔案尾
ios::trunc 如果檔案存在,則先刪除在建立
ios::binary 二進位制方式開啟檔案
多種方式開啟檔案 可用 | 連線
*/void
writetofile()
void
readfile
(int method)
//4.讀資料
switch
(method)
;while
(ifs >> buf)
break;}
case2:
;while
(ifs.
getline
(buf2,
sizeof
(buf2)))
break;}
case3:
break;}
case4:
break;}
default:}
//5.關閉檔案
ifs.
close()
;}intmain()
**解釋:
使用了四種方法來寫檔案,親自測試過的同學會發現他們的輸出結果不同。方法1讀到空格或換行,都會進行輸出;方法2和方法3都是讀一行,然後進行輸出;方法4是每讀乙個字元就輸出,所以讀到換行符時才會換行。
具體結果如下
方法1:
方法2、3、4:
text.txt文字中的儲存:
讀乙個共有20行的由數字構成的文字檔案,將裡面的資料前15行讀入到matrix1[15][10],第16到19行讀入到matrix2[4][4],第20行讀入到num中。
文字檔案如下:
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 1 0 0 0
0 0 0 0 0 0 1 0 0 0
1 1 1 0 0 0 1 1 1 1
0 0 0 0 1 0 0 0 0 0
1 0 0 0
1 0 0 0
1 0 0 0
1 0 0 0
1
**如下:
/*
20190919
讀檔案例項
*/#include
using
namespace std;
#include
int matrix1[15]
[10];
int matrix2[4]
[4];
int num;
intmain()
//讀資料
int temp_num;
for(
int i=
0; i<
15; i++)}
}for
(int i=
0; i<
4; i++)}
}if(ifs >> temp_num)
//關閉檔案
ifs.
close()
;//輸出資料
cout <<
"matrix1 :"
<
for(
int i=
0; i<
15; i++
) cout <
} cout <<
"matrix2 :"
<
for(
int i=
0; i<
4; i++
) cout <
} cout <<
"num :"
<
cout <
}
實驗結果:
C 文字讀寫操作
檔案的讀寫操作 第二種方式是使用函式,但是這些函式只是能用於處理字元,對於其它資料型別則有些有心無力了,為此還是建議使用第一種方式,因為第一種方式過載了輸入輸出操作符,它可以處理所有內建資料型別。文字檔案它的每乙個位元組存放的是乙個ascii碼,代表乙個字元。二進位制檔案是將記憶體中的資料按照其在記...
Python 文字讀寫操作
mark下讀寫操作函式,省的下次再寫 usr bin env python coding utf 8 file test.py.py author piepis date 2020 8 27 18 13 desc import os import re write data to file file...
c 檔案讀寫 文字讀寫
include int main else return 0 格式 intfscanf file stream,constchar format,返回值 如果成功,該函式返回成功匹配和賦值的個數。如果到達檔案末尾或發生讀錯誤,則返回 eof 引數1 file stream 檔案指標 引數2 cons...