什么是文件?
1、头文件介绍
#include <iostream>//标准输入输出流
#include <fstream>//派生自iostream,包括ifstream和ofstream
using namespace std;//都在名称空间std中,别忘了加上
2、打开文件
const char* fileName="1.txt";//要打开的文件名,可以使路径名,默认情况下是所建工程下
fstream类派生了两个类ifstream\ofstream
fstream f(fileName,参数二);
参数二有多种形式,这里只看主要用的几种:
ios_base::in//打开文件用于读
ios_base::out//打开文件用于写
ios_base::app//打开文件,用于追加(不覆盖原有文件,默认情况是覆盖)
ios_base::binary//以二进制方式打开文件,默认情况下是文本文件方式
例:
fstream i(fileName,ios_base::in|ios_base::out);//打开文件用于读写(既可读也可写)
ifstream in(fileName,ios_base::binary|ios_base::in);//以二进制方式打开文件用于读
ofstream out(fileName,ios_base::out|ios_base::app);//打开文件用于追加
3、由于派生自iostream,很多其他的方法和iostream一样
比如:seekg()\eof()\clear()……
4、一些文件操作的例子
读写二进制文件
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct plant
{
char name[20];
int age;
char num[10];
};
int _tmain(int argc, _TCHAR* argv[])
{
plant p;
p.name[20]=(char)"yao";
p.age=21;
p.num[10]=(char)"0950420011";
ofstream pf("data.dat",ios_base::out|ios_base::app|ios_base::binary);
pf.write((char*)&p,sizeof(p));
pf.close();
ifstream in("data.dat",ios_base::in|ios_base::binary);
plant p1;
in.read((char*)&p1,sizeof(p1));
in.close();
cout<<p1.age<<endl<<p1.name<<endl<<p1.num<<endl;
return 0;
}
循环读取指定文件的指定行
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <time.h>
//#include "iomanip.h"
//const char* file="data.dat"
using namespace std;
const int MAX=1024;
const int M=40;
//#define
//======自定义函数判断输入是否为数字=======///
bool IsDigital(const string &str)
{
//int flag=0;//字符串中数字的个数
if(str=="")
return false;
const char* p=str.c_str();
int length=str.length();
for(int i=0;i<length;i++,p++)
{
if((*p<='0')||(*p>='9'))
return false;
}
return true;
}
int _tmain(int argc, _TCHAR* argv[])
{
char c;
do
{
fstream f;
cout<<"请输入文件名称(注:先把你要打开的文件复制到本程序下,如:'file.txt')"<<endl;
int flag=0;
do
{
string str;
if(flag)
{
f.clear();
cout<<"输入文件不存在,请重新输入:"<<endl;
}
cin>>str;
const char* file=str.c_str();
//string text="";
f.open(file,ios_base::in|ios_base::out|ios_base::binary);
flag++;
}
while(!f.is_open());
int lineCount=1;//记录当前文件的总行数
int SumByte=0;//记录文件的总大小
while(!f.eof())
{
char c;
c=f.get();
if(c=='\n')
lineCount++;
SumByte++;
}
f.clear();
float kb;
kb=(float)SumByte/1024;
cout<<"当前文件的字节数是:"<<SumByte<<" Bit"<<endl;
cout<<"当前文件的总大小是:"<<kb<<" KB"<<endl;
cout<<"当前文件的总行数是: "<<lineCount<<endl;
cout<<"/*===================================================*/\n/*===================================================*/"<<endl;
int line;
string str_line;
cout<<"\n接下来请输入你要读取文件的行数:\n";
cin>>str_line;
while(!IsDigital(str_line))
{
cout<<"输入格式不正确,请重新输入:\n";
cin>>str_line;
}
line=atoi(str_line.c_str());
cout<<"当前的line值 :"<<line<<endl;
while((line<=0)||(line>lineCount))
{
cout<<"输入数据有误(1--"<<lineCount<<"间),请重新输入:\n";
cin>>line;
}
cout<<"你选择了输出第"<<line<<"行"<<endl;
//line=cin.get();
//string strOut;//输出内容
cout<<"/*===================================================*/\n/*===================================================*/"<<endl;
int count=0;
char ch;
f.seekg(0);//指向文件开始位置
for(int i=1;i<line;i++)
{
/*do
{
//f.read((char*)&ch,sizeof ch);
ch=f.get();
count++;
}
while(ch!='\n');*/
while(f.read((char*)&ch,sizeof ch))
{
count++;
if(ch=='\n')
break;
}
}
cout<<"输出count的值:"<<endl;
cout<<count<<endl;
f.seekg(count);//跳转到所选行数的开头
cout<<"/*===================================================*/\n"<<endl;
cout<<"\n接下来输出你所选择的行:\n";
cout<<"/*===================================================*/\n"<<endl;
char a;
while(f.read((char*)&a,sizeof a))
{
cout<<a;
if(a=='\n')
break;
}
cout<<""<<endl;
cout<<"是否继续打开文件?是-选择y:否-按任意键结束(除y)"<<endl;
cin>>c;
}
while(c=='y');
// char p;
//cin>>p;
return 0;
}
复制文件
#include "stdafx.h"
#include <iostream>
#include <fstream>
using namespace std;
const char* file1="1.txt";
const char* file2="2.txt";
//把文件1的内容写到文件2的末尾
int _tmain(int argc, _TCHAR* argv[])
{
ifstream in(file1);//默认方式打开文件1进行读
ofstream out(file2,ios_base::out|ios_base::app);//打开文件2进行写入(app为追加)
out<<in.rdbuf();//将文件1的内容输入到文件2的流中
in.close();//关闭文件流
out.close();
return 0;
}
到目前为止,我们已经使用了 iostream 标准库,它提供了 cin 和 cout 方法分别用于从标准输入读取流和向标准输出写入流。
本教程介绍如何从文件读取流和向文件写入流。这就需要用到 C++ 中另一个标准库 fstream,它定义了三个新的数据类型:
数据类型 | 描述 |
ofstream | 该数据类型表示输出文件流,用于创建文件并向文件写入信息。 |
ifstream | 该数据类型表示输入文件流,用于从文件读取信息。 |
fstream | 该数据类型通常表示文件流,且同时具有 ofstream 和 ifstream 两种功能,这意味着它可以创建文件,向文件写入信息,从文件读取信息。 |
要在 C++ 中进行文件处理,必须在 C++ 源代码文件中包含头文件 <iostream> 和 <fstream>。
打开文件
在从文件读取信息或者向文件写入信息之前,必须先打开文件。ofstream 和 fstream 对象都可以用来打开文件进行写操作,如果只需要打开文件进行读操作,则使用 ifstream 对象。
下面是 open() 函数的标准语法,open() 函数是 fstream、ifstream 和 ofstream 对象的一个成员。
void open(const char *filename, ios::openmode mode);
在这里,open() 成员函数的第一参数指定要打开的文件的名称和位置,第二个参数定义文件被打开的模式。
模式标志 | 描述 |
ios::app | 追加模式。所有写入都追加到文件末尾。 |
ios::ate | 文件打开后定位到文件末尾。 |
ios::in | 打开文件用于读取。 |
ios::out | 打开文件用于写入。 |
ios::trunc | 如果该文件已经存在,其内容将在打开文件之前被截断,即把文件长度设为 0。 |
您可以把以上两种或两种以上的模式结合使用。例如,如果您想要以写入模式打开文件,并希望截断文件,以防文件已存在,那么您可以使用下面的语法:
ofstream outfile;
outfile.open("file.dat", ios::out | ios::trunc );
类似地,您如果想要打开一个文件用于读写,可以使用下面的语法:
ifstream afile;
afile.open("file.dat", ios::out | ios::in );
关闭文件
当 C++ 程序终止时,它会自动关闭刷新所有流,释放所有分配的内存,并关闭所有打开的文件。但程序员应该养成一个好习惯,在程序终止前关闭所有打开的文件。
下面是 close() 函数的标准语法,close() 函数是 fstream、ifstream 和 ofstream 对象的一个成员。
void close();
写入文件
在 C++ 编程中,我们使用流插入运算符( << )向文件写入信息,就像使用该运算符输出信息到屏幕上一样。唯一不同的是,在这里您使用的是 ofstream 或 fstream 对象,而不是 cout 对象。
读取文件
在 C++ 编程中,我们使用流提取运算符( >> )从文件读取信息,就像使用该运算符从键盘输入信息一样。唯一不同的是,在这里您使用的是 ifstream 或 fstream 对象,而不是 cin 对象。
读取 & 写入实例
下面的 C++ 程序以读写模式打开一个文件。在向文件 afile.dat 写入用户输入的信息之后,程序从文件读取信息,并将其输出到屏幕上:
实例
#include <fstream>
#include <iostream>
using namespace std;
int main ()
{ char data[100];
// 以写模式打开文件 ofstream outfile;
outfile.open("afile.dat");
cout << "Writing to the file" << endl;
cout << "Enter your name: ";
cin.getline(data, 100);
// 向文件写入用户输入的数据 outfile << data << endl;
cout << "Enter your age: ";
cin >> data; cin.ignore();
// 再次向文件写入用户输入的数据 outfile << data << endl;
// 关闭打开的文件 outfile.close();
// 以读模式打开文件 ifstream infile
infile.open("afile.dat");
cout << "Reading from the file" << endl;
infile >> data;
// 在屏幕上写入数据 cout << data << endl;
// 再次从文件读取数据,并显示它 infile >> data; cout << data << endl;
// 关闭打开的文件 infile.close();
return 0; }
上面的实例中使用了 cin 对象的附加函数,比如 getline()函数从外部读取一行,ignore() 函数会忽略掉之前读语句留下的多余字符。