c语言文件创建与建立

来源:文书网 8.47K

C语言是一门通用计算机编程语言,应用广泛。下面是小编分享的c语言文件创建与建立,一起来看一下吧。

c语言文件创建与建立

今天给大家分享的是有关文件的创建与读取的语法,事实上,c语言中对于这方面的已经有相当经典且应用相当广泛的`语法了,但是我今天想讲一讲关于c++中的相关语法,以下是代码:

首先是文件的创建:

# include

# include

# include

using namespace std;

int main() {

ofstream outclientfile("", 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("", 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<<fixed<<showpoint;< p="">

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;

}

知识点以文件的创建为例,我们在头文件中使用# include包含了ofstream类,并且在主程序中使用类ofstream建立了名为outclientfile对象,并且初始化其构造函数。要注意的是我们在while只是判断条件的真假,而类outclientfile进行输入数据。

热门标签