有的语言好久不用,经常忘了基本的语法,而文件读写操作比较常用,因此记录下,以便快速参考。
1 C++
1 #include <iostream.h>
2 #include <fstream.h>
3 #include <stdlib.h>
4
5
int main()
6 {
7
//
ofstream constructor opens file
8 ofstream outClientFile(
"
clients.dat
", ios::
out );
9
10
if ( !outClientFile ) {
//
overloaded ! operator
11 cerr <<
"
File could not be opened
" << endl;
12 exit(
1 );
13 }
14
15 cout <<
"
Enter the account, name, and balance.\n
"
16 <<
"
Enter end-of-file to end input.\n?
";
17
18
int account;
19
char name[
30 ];
20
float balance;
21
22
while (cin >> account >> name >> balance ) {
23 outClientFile << account <<
'
' << name<<
'
' << balance <<
'
\n
';
24 cout <<
"
?
";
25 }
26
27
return
0;
28 }
MFC CFile CStdioFile
1 //按行读
2 CStdioFile f("test.txt",CFile::modeRead);
3 CString str;
4
5 while(f.ReadString(str))
6 {
7
8 AfxMessageBox(str);
9 }
10 f.Close();
11
12 //写
13 CStdioFile fo("testo.txt",CFile::modeWrite);
14 fo.WriteString("Haha");
15 fo.WriteString("Haha2");
16 fo.Close();
2 C#
1 StreamReader r =
new StreamReader(
@"
D:\test.txt
",Encoding.Default);
2 StreamWriter w =
new StreamWriter((
@"
D:\testout.txt
"));
3
while(!r.EndOfStream){
4
try{
5 String tmp = r.ReadLine();
6 w.WriteLine(tmp);
7
8 }
catch(Exception e){
9 }
10 }
3 Python
较为简单:
f = open(
'
filename
',
'
r
')
for line
in f.readlines():
print line ,
f.close
fo = open('foname', 'w')
fo.write('sth')
fo.close()
方法 描述
f.read([n]) 读取至多 n 字节
f.readline([n]) 读取一行中的前 n 字符。如果 n 被省略,就读取整行
f.readlines() 读取所有的行并返回一个包含所有行的列表
f.xreadlines() 返回一个迭代器,每次迭代返回文件的一个新行
f.write(s) 将字符串 s 写入文件
f.writelines(l) 将列表 l 中的所有字符串写入文件
f.close() 结束文件
f.tell() 返回当前的文件指针
f.seek(offset [, where]) 定位到一个新的文件位置
f.isatty() 如果 f 是一个交互式终端则返回 1
f.flush() 刷新输出缓冲区
f.truncate([size]) 如果文件长于 size 就截短它至 size 大小
f.fileno() 返回一个整型的文件描述符
f.readinto(buffer ,nbytes) 读取 n 字节数据至一个 buffer 对象。
内建函数
raw_input(prompt)也可以从stdin中读取并保存内容
在解释器启动时,
sys.stdout, sys.stdin及sys.stderr可以分别使用sys.stdout, sys.stdin, 和 sys.stderr这三个名字来访问。
4 Java
比较常用的文本读取、输出(还有其他的很多文件类,略去)
注意:字符流,字节流
1
//
输出
2 FileWriter fw =
new FileWriter("path");
3 PrintWriter out =
new PrintWrite(fw);
4 out.println("sth");
5
6
//
输入
7 File f =
new File("path");
8 Scanner s =
new Scanner(f);
9
while(s.hasNext()) {
10 String str = s.nextLine();
11 }