#include <iostream>
#include <fstream>
using namespace std;
// 将一个文件复制到另一个文件
int file_copy_main()
{
ifstream in;
in.open("test.txt");
if (!in)
{
cerr << "打开文件失败!" << endl;
return 0;
}
char x;
while (in >> x)
{
cout << x;
}
cout << endl;
in.close();
return 0;
}
// 将键盘输入的信息存入文件
int str_to_file_main()
{
ofstream out;
out.open("test2.txt");
if (!out)
{
cout << "打开文件失败!" << endl;
return 0;
}
for (int i = 0; i < 10; i++)
{
out << i;
}
out << endl;
out.close();
return 0;
}
int main()
{
//file_copy_main();
str_to_file_main();
return 0;
}
ifstream in;in.open("test.txt");与ifstream in("test.txt");的效果相同。
构造函数:就是对象默认使用的函数(方法)。
事实上,它还可以接受不止一个参数!
ifstream in(char *filename, int open_mode);
打开模式
|
作用
|
ios::in
|
打开一个可读取文件
|
ios::out
|
打开一个可写入文件
|
ios::binary
|
以二进制的形式打开一个文件
|
ios::app
|
写入的所有数据将被追加到文件的末尾
|
ios::trunk |
删除文件原来已存在的内容
|
ios::nocreate
|
如果要打开的文件并不存在,那么以此参数调用open函数将无法进行
|
ios::noreplace
|
如果要打开的文件已存在,试图用open函数打开时将返回一个错误。
|
// 将字符串存入文件,而后将其存入数组并显示
int str_to_file_array_main()
{
fstream fp("test.txt", ios::in | ios::out);
if (!fp)
{
cout << "打开文件失败!" << endl;
return 0;
}
fp << "Ilovecpp.";
static char str[10];
fp.seekg(ios::beg);
fp >> str;
cout << str << endl;
fp.close();
return 0;
}
输出:Ilovecpp.