簡單的文件I/O
1.創建一個ofstream對象來管理輸出流;
2.將該對象與特定的文件關聯起來;
3.以使用cout的方式使用該對象,唯一的區別是輸出將進入文件,而不是屏幕;
ofstream fout;//create an ofstream object named fout
fout.open("jar.txt");//associate fout with jar.txt
//ofstream fout("jar.txt");//also ok
fout<<"Dull Data";
注意:以這種方式打開文件來進行輸出時,如果沒有這樣的文件,將創建一個新文件;如果有這樣的文件,則打開文件將清空文件,輸出將進入到一個空文件中。(以默認模式打開文件進行輸出將自動把文件長度截短爲0,相當於刪除已有內容。)
1.創建一個ifsteam對象來管理輸入流;
2.將該對象與特定的文件關聯起來;
3.以使用cin的方式使用該對象;
//two statements
ifstream fin;
fin.open("jellyjar.txt");
//else
ifstream fis("jar.txt");
//use like cin
char ch;
fin>>ch;//read a character from the jellyjar.txt file
char buff[80];
fin>>buff;//read a word from the jellyjar.txt file
fin.getline(buf, 80);//read a line from jellyjar.txt file
//getline的80表示讀取字符串最大長度,實際79,末尾'\0'
close()方法可以顯示的關閉到文件的連接。
fout.close();//close output connection to file
fin.close();//close input connection to file
關閉這樣的連接並不會刪除流,只是斷開流到文件的連接,然而流管理裝置仍被保留,fin對象與它管理的輸入緩衝區仍然存在,可以將流重新連接到同一個文件或者另一個文件。
詳細例子:
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main() {
string filename;
cout << "Enter name for new file: ";
cin >> filename;
//create output stream object for new file and call it fout
ofstream fout(filename.c_str());
fout << "For your eyes only!\n";
cout << "Enter your secret number: ";
float secret;
cin >> secret;
fout << "Your secret number is " << secret << endl;
fout.close();
//create input stream object for new file and call it fin
ifstream fin(filename.c_str());
cout << "Here are the contents of " << filename << endl;
char ch;
fin >> ch;
cout << ch << endl;
while (fin.get(ch))
cout << ch;
cout << "Done\n";
fin.close();
system("pause");
return 0;
}
較新的C++實現提供了一種更好的檢查文件是否被打開的方法----is_open()方法。可以理解爲檢查文件是否存在
if(!fin.is_open())//open attempt failed
{
...
}
ifstream fin;
fin.open("a.txt");
fin.close();
fin.clear();//reset fin(may not be needed)
fin.open("b.txt")
fin.close();
fin.clear();
命令行模式:
#include<iostream>
#include<fstream>
#include<cstdlib>
using namespace std;
int main(int argc, char* argv[]) {
if (argc == 1) {
cerr << "Usage: " << argv[0] << "filemane[s]\n";
exit(EXIT_FAILURE);
}
ifstream fin;//open stream
long count;
long total = 0;
char ch;
for (int file = 1;file < argc;file++) {
fin.open(argv[file]);//connect stream to argv[file]
if (!fin.is_open()) {
cerr << "could not open" << argv[file] << endl;
fin.clear();
continue;
}
count = 0;
while (fin.get(ch))
count++;
cout << count << "characters in " << argv[file] << endl;
total += count;
fin.clear();
fin.close();
}
cout << total << "characters in all files\n";
system("pause");
return 0;
}
linux系統下,編譯成a.out文件,然後分別處理pairs和rome兩個文件。
$ a.out
$ a.out pairs rome
文件模式描述文件如何被使用,如讀、寫、追加等。
ifstream fin("banjo", mode1)//constructor with mode argument
ofstream fout();
fout.open("harp",mode2)//open()with mode argument
文件模式常量 之後使用一直是ios::不是ios_base::
常量 | 含義 |
---|---|
ios_base::in | 打開文件,以便讀取 |
ios_base::out | 打開文件,以便寫入 |
ios_base::ate | 打開文件,並移到文件尾 |
ios_base::app | 打開文件,追加到文件尾 |
ios_base::trunc | 如果文件存在,則截短文件 |
ios_base::binary | 二進制文件 |
與C語言文件打開模式類比
C++模式 | C模式 | 含義 |
---|---|---|
ios_base::in | “r” | 打開以讀取 |
ios_base::out | “w” | 等價於ios_base::out|ios_base::trunc |
ios_base::out|ios_base::trunc | “w” | 寫入並截短 |
ios_base::out|ios_base::app | “a” | 追加寫入 |
ios_base::in|ios_base::out | “r+” | 打開以讀寫,在文件允許位置寫入 |
ios_base::in|ios_base::out|ios_base::trunc | “w+” | 打開以讀寫,如果已經存在則截短 |
C++mode|ios_base::binary | “cmodeb” | 以C++mode和二進制模式打開 |
C++mode|ios_base::ate | “cmode” | 以指定模式打開,並移到文件尾 |
注意: ios_base::ate和ios_base::app都將文件指針指向打開的文件尾。二者的區別在於,ios_base::app模式只允許將數字添加到文件尾,而ios_base::ate模式將指針放到文件尾。
具體例子:
#include<iostream>
#include<fstream>
#include<string>
#include<cstdlib>
using namespace std;
const char* file = "guests.txt";
int main() {
char ch;
//show initial contents
ifstream fin;
fin.open(file);
if (fin.is_open()) {
cout << "Here are the current contents of the " << file << " file:\n";
while (fin.get(ch))
cout << ch;
fin.close();
}
//add new names
ofstream fout(file, ios::out | ios_base::app);//ios和ios_base都可以
if (!fout.is_open()) {
cerr << "Cant open" << file << " for output.\n";
exit(EXIT_FAILURE);
}
cout << "Enter guest names(enter a blank line to quit):\n";
string name;
while (getline(cin, name) && name.size() > 0) {
fout << name << endl;
}
fout.close();
//show revised file
fin.clear();
fin.open(file);
if (fin.is_open()) {
cout << "Here are the new contents of the " << file << " file:\n";
while (fin.get(ch))
cout << ch;
fin.close();
}
cout << "Done.\n";
system("pause");
return 0;
}