天天看點

fstream無法建立檔案

#include<fstream>
#include<string>
#include<iostream>
using namespace std;
int main() {
	string str[6]= {"sbzdh", "sbzh", "sbczl"};
	fstream fs;
	fs.open("test1.txt" /*, ios_base::out*/);
	fs<< str[0]<< str[1]<< str[2];
	fs>> str[3]>> str[4]>> str[5];
	cout<< str[3]<<" "<< 0<< endl;
	cout<< str[4]<<" "<< 1<< endl;
	cout<< str[5]<<" "<< 2<< endl;
}


//前面的代碼fs不能輸出到str[3,4,5]中,也沒有建立檔案


/*
#include<fstream>
#include<string>
#include<iostream>
using namespace std;
int main() {
	string str[6]= {"sbzdh", "sbzh", "sbczl"};
	ofstream ofs;
	ofs.open("test1.txt");
	ofs<< str[0]<< str[1]<< str[2];
	ofs.close();
	ifstream ifs("test1.txt");
	ifs>> str[3]>> str[4]>> str[5];
	cout<< str[3]<<" "<< 0<< endl;
	cout<< str[4]<<" "<< 1<< endl;
	cout<< str[5]<<" "<< 2<< endl;
}
*/
           

今天測試了一下檔案輸出後的儲存格式,輸出流并不會幫每一個資料間添加空格!這是原先想要的。

意外收獲:

fstream不能建立新的檔案

原因(來自:http://bbs.csdn.net/topics/340213240)

如果你以in|out的方式打開檔案,則要求檔案必須已經存在,這是由in選項決定的; 

當參數為ios::out| ios::in 檔案不存在是不會被建立的。事實上隻要有ios::in 就不會被建立

或者你可以使用in|out|trunc打開, 

這樣如果檔案不存在,将被建立; 

但如果被打開的檔案存在,他的内容将被清空。

c++

繼續閱讀