C語(yǔ)言文件的創(chuàng)建與建立
c語(yǔ)言中對(duì)于文件的創(chuàng)建與建立已經(jīng)有相當(dāng)經(jīng)典且應(yīng)用相當(dāng)廣泛的語(yǔ)法了。下面是小編為大家?guī)?lái)的C語(yǔ)言文件的創(chuàng)建與建立的知識(shí),歡迎閱讀。
首先是文件的創(chuàng)建:
# include
# include
# include
using namespace std;
int main() {
ofstream outclientfile("clients.dat", ios::out);
if (!outclientfile) {
cerr << "file could not be opend" << endl;
exit(1);
}
cout << "enter the account,name,and balance." << endl;
cout<< "enter end-of-file to end input. ?";
int account;
char name[30];
double balance;
while (cin >> account >> name >> balance) {
outclientfile << account << " " << name << " " << balance << endl;
cout << "?";
}
system("pause");
return 0;
}
以下是文件的讀取:
# include
# include
# include
# include
# include
using namespace std;
void outputline(int, const string, double);
int main() {
ifstream inclientfile("clients.dat", ios::in);
if (!inclientfile) {
cerr << "file could not be opened" << endl;
exit(1);
}
int account;
char name[30];
double balance;
cout << left << setw(10) << "account" << setw(13) << "name"
<< "balance" << endl<
while (inclientfile >> account >> name >> balance) {
outputline(account, name, balance);
}
system("pause");
return 0;
}
void outputline(int account, const string name, double balance) {
cout << left << setw(10) << account << setw(13) << name
<< setw(7) << setprecision(2) << right << balance << endl;
}
知識(shí)點(diǎn):以文件的創(chuàng)建為例,我們?cè)陬^文件中使用# include包含了ofstream類(lèi),并且在主程序中使用類(lèi)ofstream建立了名為outclientfile對(duì)象,并且初始化其構(gòu)造函數(shù)。要注意的是我們?cè)趙hile只是判斷條件的真假,而類(lèi)outclientfile進(jìn)行輸入數(shù)據(jù),在這里我也有疑問(wèn)的是?在編譯為什么是出現(xiàn)在輸入數(shù)據(jù)之前的?這一點(diǎn)以后明白了再找機(jī)會(huì)說(shuō)明,或者有知道的小伙伴也可以發(fā)消息告知我一下?
【C語(yǔ)言文件的創(chuàng)建與建立】相關(guān)文章:
怎么利用c語(yǔ)言創(chuàng)建excel文件08-13
C語(yǔ)言文件03-02
C語(yǔ)言的文件概念07-18
C語(yǔ)言文件操作的方法03-29
C語(yǔ)言文件操作函數(shù)05-22
C語(yǔ)言頭文件封裝06-25
C語(yǔ)言文件操作教程05-11