read\write in C++ from file
2016-11-21 10:14
465 查看
C++ 简单读写文本文件、统计文件的行数、读取文件数据到数组
fstream提供了三个类,用来实现c++对文件的操作。(文件的创建、读、写)。
ifstream -- 从已有的文件读
ofstream -- 向文件写内容
fstream - 打开文件供读写
文件打开模式:
ios::in 读
ios::out 写
ios::app 从文件末尾开始写
ios::binary 二进制模式
ios::nocreate 打开一个文件时,如果文件不存在,不创建文件。
ios::noreplace 打开一个文件时,如果文件不存在,创建该文件
ios::trunc 打开一个文件,然后清空内容
ios::ate 打开一个文件时,将位置移动到文件尾
文件指针位置在c++中的用法:
ios::beg 文件头
ios::end 文件尾
ios::cur 当前位置
例子:
file.seekg(0,ios::beg); //让文件指针定位到文件开头
file.seekg(0,ios::end); //让文件指针定位到文件末尾
file.seekg(10,ios::cur); //让文件指针从当前位置向文件末方向移动10个字节
file.seekg(-10,ios::cur); //让文件指针从当前位置向文件开始方向移动10个字节
file.seekg(10,ios::beg); //让文件指针定位到离文件开头10个字节的位置
常用的错误判断方法:
good() 如果文件打开成功
bad() 打开文件时发生错误
eof() 到达文件尾
实例:
一、写入文件
#include <iostream>
#include <fstream>
using namespace std;
void main()
{
ofstream in;
in.open("com.txt",ios::trunc); //ios::trunc表示在打开文件前将文件清空,由于是写入,文件不存在则创建
int i;
char a='a';
for(i=1;i<=26;i++)//将26个数字及英文字母写入文件
{
if(i<10)
{
in<<"0"<<i<<"\t"<<a<<"\n";
a++;
}
else
{
in<<i<<"\t"<<a<<"\n";
a++;
}
}
in.close();//关闭文件
}
打开com.txt,效果如下:
二、读取文件
上面仅仅是将文本写入文件,并没有读取出来。
以下为读取文件的一种方法:将文件每行内容存储到字符串中,再输出字符串
#include <iostream>
#include <fstream>
using namespace std;
void main()
{
char buffer[256];
fstream out;
out.open("com.txt",ios::in);
cout<<"com.txt"<<" 的内容如下:"<<endl;
while(!out.eof())
{
out.getline(buffer,256,'\n');//getline(char *,int,char) 表示该行字符达到256个或遇到换行就结束
cout<<buffer<<endl;
}
out.close();
cin.get();//cin.get() 是用来读取回车键的,如果没这一行,输出的结果一闪就消失了
}
逐个字符的读取文件:
#include <iostream>
#include <fstream>
using namespace std;
void main()
{
fstream in;
char c;
in.open("comn.txt",ios::in);
while(!in.eof())
{
in>>c;
cout<<c;
}
in.close();
cin.get();
}
这个方法读取的文件,所有字符都一起显示,不会分行。这里字母z显示两次,是正常的,因为在输出文件最后一个字母z之后,又输出了一次(可以仔细考虑程序代码)。
读取文件某一行内容:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int CountLines(char *filename)
{
ifstream ReadFile;
int n=0;
string tmp;
ReadFile.open(filename,ios::in);//ios::in 表示以只读的方式读取文件
if(ReadFile.fail())//文件打开失败:返回0
{
return 0;
}
else//文件存在
{
while(getline(ReadFile,tmp))
{
n++;
}
return n;
}
ReadFile.close();
}
string ReadLine(char *filename,int line)
{
int lines,i=0;
string temp;
fstream file;
file.open(filename,ios::in);
lines=CountLines(filename);
if(line<=0)
{
return "Error 1: 行数错误,不能为0或负数。";
}
if(file.fail())
{
return "Error 2: 文件不存在。";
}
if(line>lines)
{
return "Error 3: 行数超出文件长度。";
}
while(getline(file,temp)&&i<line-1)
{
i++;
}
file.close();
return temp;
}
void main()
{
int l;
char filename[256];
cout<<"请输入文件名:"<<endl;
cin>>filename;
cout<<"\n请输入要读取的行数:"<<endl;
cin>>l;
cout<<ReadLine(filename,l);
cin.get();
cin.get();
}
很显然,根据以上程序,利用循环,可以逐行读取整个文件内容。
三、统计文件的行数
#include <iostream>
#include <fstream>
using namespace std;
int CountLines(char *filename)
{
ifstream ReadFile;
int n=0;
char line[512];
ReadFile.open(filename,ios::in);//ios::in 表示以只读的方式读取文件
if(ReadFile.fail())//文件打开失败:返回0
{
return 0;
}
else//文件存在
{
while(!ReadFile.eof())
{
ReadFile.getline(line,512,'\n');
n++;
}
return n;
}
ReadFile.close();
}
void main()
{
cout<<"comn.txt的行数为: "<<CountLines("comn.txt")<<endl;
cin.get();
}
以上程序的设计思路没有问题,但在实际操作的时候会发现统计出的行数与实际不符,原因在于ReadFile.getline(line,512,'\n')这一句:当一行字符超过512或遇到回车之后,行数自动加1.如果换行符在新的一行,返回的结果会比实际多1;如果不在新的一行,返回结果与实际相符。可以修改如下:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int CountLines(char *filename)
{
ifstream ReadFile;
int n=0;
char line[512];
string temp;
ReadFile.open(filename,ios::in);//ios::in 表示以只读的方式读取文件
if(ReadFile.fail())//文件打开失败:返回0
{
return 0;
}
else//文件存在
{
while(getline(ReadFile,temp))
{
n++;
}
return n;
}
ReadFile.close();
}
void main()
{
cout<<"comn.txt的行数为: "<<CountLines("comn.txt")<<endl;
cin.get();
}
四、读取文件数据到数组
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int CountLines(char *filename)//获取文件的行数
{
ifstream ReadFile;
int n=0;
string temp;
ReadFile.open(filename,ios::in);//ios::in 表示以只读的方式读取文件
if(ReadFile.fail())//文件打开失败:返回0
{
return 0;
}
else//文件存在,返回文件行数
{
while(getline(ReadFile,temp))
{
n++;
}
return n;
}
ReadFile.close();
}
void main()
{
ifstream file;
int LINES;
char filename[512];
cout<<"请输入要打开的文件名:"<<endl;
cin>>filename;
file.open(filename,ios::in);
if(file.fail())
{
cout<<"文件不存在."<<endl;
file.close();
cin.get();
cin.get();
}
else//文件存在
{
LINES=CountLines(filename);
int *tc=new int[LINES];
char *t=new char[LINES];
int i=0;
while(!file.eof()) //读取数据到数组
{
file>>tc[i];
file>>t[i];
i++;
}
file.close(); //关闭文件
for(i=0;i<LINES;i++)//输出数组内容
cout<<tc[i]<<"\t"<<t[i]<<endl;
cin.get();
cin.get();
}
}
C++ 简单读写文本文件、统计文件的行数、读取文件数据到数组
fstream提供了三个类,用来实现c++对文件的操作。(文件的创建、读、写)。
ifstream -- 从已有的文件读
ofstream -- 向文件写内容
fstream - 打开文件供读写
文件打开模式:
ios::in 读
ios::out 写
ios::app 从文件末尾开始写
ios::binary 二进制模式
ios::nocreate 打开一个文件时,如果文件不存在,不创建文件。
ios::noreplace 打开一个文件时,如果文件不存在,创建该文件
ios::trunc 打开一个文件,然后清空内容
ios::ate 打开一个文件时,将位置移动到文件尾
文件指针位置在c++中的用法:
ios::beg 文件头
ios::end 文件尾
ios::cur 当前位置
例子:
file.seekg(0,ios::beg); //让文件指针定位到文件开头
file.seekg(0,ios::end); //让文件指针定位到文件末尾
file.seekg(10,ios::cur); //让文件指针从当前位置向文件末方向移动10个字节
file.seekg(-10,ios::cur); //让文件指针从当前位置向文件开始方向移动10个字节
file.seekg(10,ios::beg); //让文件指针定位到离文件开头10个字节的位置
常用的错误判断方法:
good() 如果文件打开成功
bad() 打开文件时发生错误
eof() 到达文件尾
实例:
一、写入文件
#include <iostream>
#include <fstream>
using namespace std;
void main()
{
ofstream in;
in.open("com.txt",ios::trunc); //ios::trunc表示在打开文件前将文件清空,由于是写入,文件不存在则创建
int i;
char a='a';
for(i=1;i<=26;i++)//将26个数字及英文字母写入文件
{
if(i<10)
{
in<<"0"<<i<<"\t"<<a<<"\n";
a++;
}
else
{
in<<i<<"\t"<<a<<"\n";
a++;
}
}
in.close();//关闭文件
}
打开com.txt,效果如下:
二、读取文件
上面仅仅是将文本写入文件,并没有读取出来。
以下为读取文件的一种方法:将文件每行内容存储到字符串中,再输出字符串
#include <iostream>
#include <fstream>
using namespace std;
void main()
{
char buffer[256];
fstream out;
out.open("com.txt",ios::in);
cout<<"com.txt"<<" 的内容如下:"<<endl;
while(!out.eof())
{
out.getline(buffer,256,'\n');//getline(char *,int,char) 表示该行字符达到256个或遇到换行就结束
cout<<buffer<<endl;
}
out.close();
cin.get();//cin.get() 是用来读取回车键的,如果没这一行,输出的结果一闪就消失了
}
逐个字符的读取文件:
#include <iostream>
#include <fstream>
using namespace std;
void main()
{
fstream in;
char c;
in.open("comn.txt",ios::in);
while(!in.eof())
{
in>>c;
cout<<c;
}
in.close();
cin.get();
}
这个方法读取的文件,所有字符都一起显示,不会分行。这里字母z显示两次,是正常的,因为在输出文件最后一个字母z之后,又输出了一次(可以仔细考虑程序代码)。
读取文件某一行内容:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int CountLines(char *filename)
{
ifstream ReadFile;
int n=0;
string tmp;
ReadFile.open(filename,ios::in);//ios::in 表示以只读的方式读取文件
if(ReadFile.fail())//文件打开失败:返回0
{
return 0;
}
else//文件存在
{
while(getline(ReadFile,tmp))
{
n++;
}
return n;
}
ReadFile.close();
}
string ReadLine(char *filename,int line)
{
int lines,i=0;
string temp;
fstream file;
file.open(filename,ios::in);
lines=CountLines(filename);
if(line<=0)
{
return "Error 1: 行数错误,不能为0或负数。";
}
if(file.fail())
{
return "Error 2: 文件不存在。";
}
if(line>lines)
{
return "Error 3: 行数超出文件长度。";
}
while(getline(file,temp)&&i<line-1)
{
i++;
}
file.close();
return temp;
}
void main()
{
int l;
char filename[256];
cout<<"请输入文件名:"<<endl;
cin>>filename;
cout<<"\n请输入要读取的行数:"<<endl;
cin>>l;
cout<<ReadLine(filename,l);
cin.get();
cin.get();
}
很显然,根据以上程序,利用循环,可以逐行读取整个文件内容。
三、统计文件的行数
#include <iostream>
#include <fstream>
using namespace std;
int CountLines(char *filename)
{
ifstream ReadFile;
int n=0;
char line[512];
ReadFile.open(filename,ios::in);//ios::in 表示以只读的方式读取文件
if(ReadFile.fail())//文件打开失败:返回0
{
return 0;
}
else//文件存在
{
while(!ReadFile.eof())
{
ReadFile.getline(line,512,'\n');
n++;
}
return n;
}
ReadFile.close();
}
void main()
{
cout<<"comn.txt的行数为: "<<CountLines("comn.txt")<<endl;
cin.get();
}
以上程序的设计思路没有问题,但在实际操作的时候会发现统计出的行数与实际不符,原因在于ReadFile.getline(line,512,'\n')这一句:当一行字符超过512或遇到回车之后,行数自动加1.如果换行符在新的一行,返回的结果会比实际多1;如果不在新的一行,返回结果与实际相符。可以修改如下:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int CountLines(char *filename)
{
ifstream ReadFile;
int n=0;
char line[512];
string temp;
ReadFile.open(filename,ios::in);//ios::in 表示以只读的方式读取文件
if(ReadFile.fail())//文件打开失败:返回0
{
return 0;
}
else//文件存在
{
while(getline(ReadFile,temp))
{
n++;
}
return n;
}
ReadFile.close();
}
void main()
{
cout<<"comn.txt的行数为: "<<CountLines("comn.txt")<<endl;
cin.get();
}
四、读取文件数据到数组
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int CountLines(char *filename)//获取文件的行数
{
ifstream ReadFile;
int n=0;
string temp;
ReadFile.open(filename,ios::in);//ios::in 表示以只读的方式读取文件
if(ReadFile.fail())//文件打开失败:返回0
{
return 0;
}
else//文件存在,返回文件行数
{
while(getline(ReadFile,temp))
{
n++;
}
return n;
}
ReadFile.close();
}
void main()
{
ifstream file;
int LINES;
char filename[512];
cout<<"请输入要打开的文件名:"<<endl;
cin>>filename;
file.open(filename,ios::in);
if(file.fail())
{
cout<<"文件不存在."<<endl;
file.close();
cin.get();
cin.get();
}
else//文件存在
{
LINES=CountLines(filename);
int *tc=new int[LINES];
char *t=new char[LINES];
int i=0;
while(!file.eof()) //读取数据到数组
{
file>>tc[i];
file>>t[i];
i++;
}
file.close(); //关闭文件
for(i=0;i<LINES;i++)//输出数组内容
cout<<tc[i]<<"\t"<<t[i]<<endl;
cin.get();
cin.get();
}
}
原文地址:ifstream用法作者:yu_ynan
ofstream 和ifstream的具体用法
2008-03-30 23:38:转自:http://hi.baidu.com/sibeichen055/blog/item/e81aca3398d807fc1b4cff78.html
ofstream ifstream 文件操作
////////////////////////////////////////////////////
2009-11-15 11:18转自http://hi.baidu.com/bigbigrabbit/blog/item/9122d1a823337ff61e17a2ed.html
fstream提供了三个类,用来实现c++对文件的操作。(文件的创建、读、写)。
ifstream -- 从已有的文件读
ofstream -- 向文件写内容
fstream - 打开文件供读写
文件打开模式:
ios::in 读
ios::out 写
ios::app 从文件末尾开始写
ios::binary 二进制模式
ios::nocreate 打开一个文件时,如果文件不存在,不创建文件。
ios::noreplace 打开一个文件时,如果文件不存在,创建该文件
ios::trunc 打开一个文件,然后清空内容
ios::ate 打开一个文件时,将位置移动到文件尾
文件指针位置在c++中的用法:
ios::beg 文件头
ios::end 文件尾
ios::cur 当前位置
例子:
file.seekg(0,ios::beg); //让文件指针定位到文件开头
file.seekg(0,ios::end); //让文件指针定位到文件末尾
file.seekg(10,ios::cur); //让文件指针从当前位置向文件末方向移动10个字节
file.seekg(-10,ios::cur); //让文件指针从当前位置向文件开始方向移动10个字节
file.seekg(10,ios::beg); //让文件指针定位到离文件开头10个字节的位置
常用的错误判断方法:
good() 如果文件打开成功
bad() 打开文件时发生错误
eof() 到达文件尾
实例:
一、写入文件
#include <iostream>
#include <fstream>
using namespace std;
void main()
{
ofstream in;
in.open("com.txt",ios::trunc); //ios::trunc表示在打开文件前将文件清空,由于是写入,文件不存在则创建
int i;
char a='a';
for(i=1;i<=26;i++)//将26个数字及英文字母写入文件
{
if(i<10)
{
in<<"0"<<i<<"\t"<<a<<"\n";
a++;
}
else
{
in<<i<<"\t"<<a<<"\n";
a++;
}
}
in.close();//关闭文件
}
打开com.txt,效果如下:
二、读取文件
上面仅仅是将文本写入文件,并没有读取出来。
以下为读取文件的一种方法:将文件每行内容存储到字符串中,再输出字符串
#include <iostream>
#include <fstream>
using namespace std;
void main()
{
char buffer[256];
fstream out;
out.open("com.txt",ios::in);
cout<<"com.txt"<<" 的内容如下:"<<endl;
while(!out.eof())
{
out.getline(buffer,256,'\n');//getline(char *,int,char) 表示该行字符达到256个或遇到换行就结束
cout<<buffer<<endl;
}
out.close();
cin.get();//cin.get() 是用来读取回车键的,如果没这一行,输出的结果一闪就消失了
}
逐个字符的读取文件:
#include <iostream>
#include <fstream>
using namespace std;
void main()
{
fstream in;
char c;
in.open("comn.txt",ios::in);
while(!in.eof())
{
in>>c;
cout<<c;
}
in.close();
cin.get();
}
这个方法读取的文件,所有字符都一起显示,不会分行。这里字母z显示两次,是正常的,因为在输出文件最后一个字母z之后,又输出了一次(可以仔细考虑程序代码)。
读取文件某一行内容:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int CountLines(char *filename)
{
ifstream ReadFile;
int n=0;
string tmp;
ReadFile.open(filename,ios::in);//ios::in 表示以只读的方式读取文件
if(ReadFile.fail())//文件打开失败:返回0
{
return 0;
}
else//文件存在
{
while(getline(ReadFile,tmp))
{
n++;
}
return n;
}
ReadFile.close();
}
string ReadLine(char *filename,int line)
{
int lines,i=0;
string temp;
fstream file;
file.open(filename,ios::in);
lines=CountLines(filename);
if(line<=0)
{
return "Error 1: 行数错误,不能为0或负数。";
}
if(file.fail())
{
return "Error 2: 文件不存在。";
}
if(line>lines)
{
return "Error 3: 行数超出文件长度。";
}
while(getline(file,temp)&&i<line-1)
{
i++;
}
file.close();
return temp;
}
void main()
{
int l;
char filename[256];
cout<<"请输入文件名:"<<endl;
cin>>filename;
cout<<"\n请输入要读取的行数:"<<endl;
cin>>l;
cout<<ReadLine(filename,l);
cin.get();
cin.get();
}
很显然,根据以上程序,利用循环,可以逐行读取整个文件内容。
三、统计文件的行数
#include <iostream>
#include <fstream>
using namespace std;
int CountLines(char *filename)
{
ifstream ReadFile;
int n=0;
char line[512];
ReadFile.open(filename,ios::in);//ios::in 表示以只读的方式读取文件
if(ReadFile.fail())//文件打开失败:返回0
{
return 0;
}
else//文件存在
{
while(!ReadFile.eof())
{
ReadFile.getline(line,512,'\n');
n++;
}
return n;
}
ReadFile.close();
}
void main()
{
cout<<"comn.txt的行数为: "<<CountLines("comn.txt")<<endl;
cin.get();
}
以上程序的设计思路没有问题,但在实际操作的时候会发现统计出的行数与实际不符,原因在于ReadFile.getline(line,512,'\n')这一句:当一行字符超过512或遇到回车之后,行数自动加1.如果换行符在新的一行,返回的结果会比实际多1;如果不在新的一行,返回结果与实际相符。可以修改如下:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int CountLines(char *filename)
{
ifstream ReadFile;
int n=0;
char line[512];
string temp;
ReadFile.open(filename,ios::in);//ios::in 表示以只读的方式读取文件
if(ReadFile.fail())//文件打开失败:返回0
{
return 0;
}
else//文件存在
{
while(getline(ReadFile,temp))
{
n++;
}
return n;
}
ReadFile.close();
}
void main()
{
cout<<"comn.txt的行数为: "<<CountLines("comn.txt")<<endl;
cin.get();
}
四、读取文件数据到数组
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int CountLines(char *filename)//获取文件的行数
{
ifstream ReadFile;
int n=0;
string temp;
ReadFile.open(filename,ios::in);//ios::in 表示以只读的方式读取文件
if(ReadFile.fail())//文件打开失败:返回0
{
return 0;
}
else//文件存在,返回文件行数
{
while(getline(ReadFile,temp))
{
n++;
}
return n;
}
ReadFile.close();
}
void main()
{
ifstream file;
int LINES;
char filename[512];
cout<<"请输入要打开的文件名:"<<endl;
cin>>filename;
file.open(filename,ios::in);
if(file.fail())
{
cout<<"文件不存在."<<endl;
file.close();
cin.get();
cin.get();
}
else//文件存在
{
LINES=CountLines(filename);
int *tc=new int[LINES];
char *t=new char[LINES];
int i=0;
while(!file.eof()) //读取数据到数组
{
file>>tc[i];
file>>t[i];
i++;
}
file.close(); //关闭文件
for(i=0;i<LINES;i++)//输出数组内容
cout<<tc[i]<<"\t"<<t[i]<<endl;
cin.get();
cin.get();
}
}
C++ 简单读写文本文件、统计文件的行数、读取文件数据到数组
fstream提供了三个类,用来实现c++对文件的操作。(文件的创建、读、写)。
ifstream -- 从已有的文件读
ofstream -- 向文件写内容
fstream - 打开文件供读写
文件打开模式:
ios::in 读
ios::out 写
ios::app 从文件末尾开始写
ios::binary 二进制模式
ios::nocreate 打开一个文件时,如果文件不存在,不创建文件。
ios::noreplace 打开一个文件时,如果文件不存在,创建该文件
ios::trunc 打开一个文件,然后清空内容
ios::ate 打开一个文件时,将位置移动到文件尾
文件指针位置在c++中的用法:
ios::beg 文件头
ios::end 文件尾
ios::cur 当前位置
例子:
file.seekg(0,ios::beg); //让文件指针定位到文件开头
file.seekg(0,ios::end); //让文件指针定位到文件末尾
file.seekg(10,ios::cur); //让文件指针从当前位置向文件末方向移动10个字节
file.seekg(-10,ios::cur); //让文件指针从当前位置向文件开始方向移动10个字节
file.seekg(10,ios::beg); //让文件指针定位到离文件开头10个字节的位置
常用的错误判断方法:
good() 如果文件打开成功
bad() 打开文件时发生错误
eof() 到达文件尾
实例:
一、写入文件
#include <iostream>
#include <fstream>
using namespace std;
void main()
{
ofstream in;
in.open("com.txt",ios::trunc); //ios::trunc表示在打开文件前将文件清空,由于是写入,文件不存在则创建
int i;
char a='a';
for(i=1;i<=26;i++)//将26个数字及英文字母写入文件
{
if(i<10)
{
in<<"0"<<i<<"\t"<<a<<"\n";
a++;
}
else
{
in<<i<<"\t"<<a<<"\n";
a++;
}
}
in.close();//关闭文件
}
打开com.txt,效果如下:
二、读取文件
上面仅仅是将文本写入文件,并没有读取出来。
以下为读取文件的一种方法:将文件每行内容存储到字符串中,再输出字符串
#include <iostream>
#include <fstream>
using namespace std;
void main()
{
char buffer[256];
fstream out;
out.open("com.txt",ios::in);
cout<<"com.txt"<<" 的内容如下:"<<endl;
while(!out.eof())
{
out.getline(buffer,256,'\n');//getline(char *,int,char) 表示该行字符达到256个或遇到换行就结束
cout<<buffer<<endl;
}
out.close();
cin.get();//cin.get() 是用来读取回车键的,如果没这一行,输出的结果一闪就消失了
}
逐个字符的读取文件:
#include <iostream>
#include <fstream>
using namespace std;
void main()
{
fstream in;
char c;
in.open("comn.txt",ios::in);
while(!in.eof())
{
in>>c;
cout<<c;
}
in.close();
cin.get();
}
这个方法读取的文件,所有字符都一起显示,不会分行。这里字母z显示两次,是正常的,因为在输出文件最后一个字母z之后,又输出了一次(可以仔细考虑程序代码)。
读取文件某一行内容:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int CountLines(char *filename)
{
ifstream ReadFile;
int n=0;
string tmp;
ReadFile.open(filename,ios::in);//ios::in 表示以只读的方式读取文件
if(ReadFile.fail())//文件打开失败:返回0
{
return 0;
}
else//文件存在
{
while(getline(ReadFile,tmp))
{
n++;
}
return n;
}
ReadFile.close();
}
string ReadLine(char *filename,int line)
{
int lines,i=0;
string temp;
fstream file;
file.open(filename,ios::in);
lines=CountLines(filename);
if(line<=0)
{
return "Error 1: 行数错误,不能为0或负数。";
}
if(file.fail())
{
return "Error 2: 文件不存在。";
}
if(line>lines)
{
return "Error 3: 行数超出文件长度。";
}
while(getline(file,temp)&&i<line-1)
{
i++;
}
file.close();
return temp;
}
void main()
{
int l;
char filename[256];
cout<<"请输入文件名:"<<endl;
cin>>filename;
cout<<"\n请输入要读取的行数:"<<endl;
cin>>l;
cout<<ReadLine(filename,l);
cin.get();
cin.get();
}
很显然,根据以上程序,利用循环,可以逐行读取整个文件内容。
三、统计文件的行数
#include <iostream>
#include <fstream>
using namespace std;
int CountLines(char *filename)
{
ifstream ReadFile;
int n=0;
char line[512];
ReadFile.open(filename,ios::in);//ios::in 表示以只读的方式读取文件
if(ReadFile.fail())//文件打开失败:返回0
{
return 0;
}
else//文件存在
{
while(!ReadFile.eof())
{
ReadFile.getline(line,512,'\n');
n++;
}
return n;
}
ReadFile.close();
}
void main()
{
cout<<"comn.txt的行数为: "<<CountLines("comn.txt")<<endl;
cin.get();
}
以上程序的设计思路没有问题,但在实际操作的时候会发现统计出的行数与实际不符,原因在于ReadFile.getline(line,512,'\n')这一句:当一行字符超过512或遇到回车之后,行数自动加1.如果换行符在新的一行,返回的结果会比实际多1;如果不在新的一行,返回结果与实际相符。可以修改如下:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int CountLines(char *filename)
{
ifstream ReadFile;
int n=0;
char line[512];
string temp;
ReadFile.open(filename,ios::in);//ios::in 表示以只读的方式读取文件
if(ReadFile.fail())//文件打开失败:返回0
{
return 0;
}
else//文件存在
{
while(getline(ReadFile,temp))
{
n++;
}
return n;
}
ReadFile.close();
}
void main()
{
cout<<"comn.txt的行数为: "<<CountLines("comn.txt")<<endl;
cin.get();
}
四、读取文件数据到数组
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int CountLines(char *filename)//获取文件的行数
{
ifstream ReadFile;
int n=0;
string temp;
ReadFile.open(filename,ios::in);//ios::in 表示以只读的方式读取文件
if(ReadFile.fail())//文件打开失败:返回0
{
return 0;
}
else//文件存在,返回文件行数
{
while(getline(ReadFile,temp))
{
n++;
}
return n;
}
ReadFile.close();
}
void main()
{
ifstream file;
int LINES;
char filename[512];
cout<<"请输入要打开的文件名:"<<endl;
cin>>filename;
file.open(filename,ios::in);
if(file.fail())
{
cout<<"文件不存在."<<endl;
file.close();
cin.get();
cin.get();
}
else//文件存在
{
LINES=CountLines(filename);
int *tc=new int[LINES];
char *t=new char[LINES];
int i=0;
while(!file.eof()) //读取数据到数组
{
file>>tc[i];
file>>t[i];
i++;
}
file.close(); //关闭文件
for(i=0;i<LINES;i++)//输出数组内容
cout<<tc[i]<<"\t"<<t[i]<<endl;
cin.get();
cin.get();
}
}
原文地址:ifstream用法作者:yu_ynan
ofstream 和ifstream的具体用法
2008-03-30 23:38:转自:http://hi.baidu.com/sibeichen055/blog/item/e81aca3398d807fc1b4cff78.html
这个小知识点迷糊了很久了,前段时间始终没有搞清楚,今天又拿过来看的时候好象明白了点...... 今天将ifstream 与ofstream的用法归纳一下 ofstream是从内存到硬盘,ifstream是从硬盘到内存,其实所谓的流缓冲就是内存空间; 在C 中,有一个stream这个类,所有的I/O都以这个“流”类为基础的,包括我们要认识的文件I/O,stream这个类有两个重要的运算符: 1、插入器(<<) 向流输出数据。比如说系统有一个默认的标准输出流(cout),一般情况下就是指的显示器,所以,cout<<"Write Stdout"<<'n';就表示把字符串"Write Stdout"和换行字符('n')输出到标准输出流。 2、析取器(>>) 从流中输入数据。比如说系统有一个默认的标准输入流(cin),一般情况下就是指的键盘,所以,cin>>x;就表示从标准输入流中读取一个指定类型(即变量x的类型)的数据。 在C 中,对文件的操作是通过stream的子类fstream(file stream)来实现的,所以,要用这种方式操作文件,就必须加入头文件fstream.h。下面就把此类的文件操作过程一一道来。 一、打开文件 在fstream类中,有一个成员函数open(),就是用来打开文件的,其原型是: void open(const char* filename,int mode,int access); 参数: filename: 要打开的文件名 mode: 要打开文件的方式 access: 打开文件的属性 打开文件的方式在类ios(是所有流式I/O类的基类)中定义,常用的值如下: ios::app: 以追加的方式打开文件 ios::ate: 文件打开后定位到文件尾,ios:app就包含有此属性 ios::binary: 以二进制方式打开文件,缺省的方式是文本方式。两种方式的区别见前文 ios::in: 文件以输入方式打开(文件数据输入到内存) ios::out: 文件以输出方式打开(内存数据输出到文件) ios::nocreate: 不建立文件,所以文件不存在时打开失败 ios::noreplace:不覆盖文件,所以打开文件时如果文件存在失败 ios::trunc: 如果文件存在,把文件长度设为0 可以用“或”把以上属性连接起来,如ios::out|ios::binary 打开文件的属性取值是: 0:普通文件,打开访问 1:只读文件 2:隐含文件 4:系统文件 可以用“或”或者“ ”把以上属性连接起来,如3或1|2就是以只读和隐含属性打开文件。 例如:以二进制输入方式打开文件c:config.sys fstream file1; file1.open("c:\config.sys",ios::binary|ios::in,0); 如果open函数只有文件名一个参数,则是以读/写普通文件打开,即: file1.open("c:\config.sys"); <=> file1.open("c:\config.sys",ios::in|ios::out,0); 另外,fstream还有和open()一样的构造函数,对于上例,在定义的时侯就可以打开文件了: fstream file1("c:\config.sys"); 特别提出的是,fstream有两个子类:ifstream(input file stream)和ofstream(outpu file stream),ifstream默认以输入方式打开文件,而ofstream默认以输出方式打开文件。 ifstream file2("c:\pdos.def");//以输入方式打开文件 ofstream file3("c:\x.123");//以输出方式打开文件 所以,在实际应用中,根据需要的不同,选择不同的类来定义:如果想以输入方式打开,就用ifstream来定义;如果想以输出方式打开,就用ofstream来定义;如果想以输入/输出方式来打开,就用fstream来定义。 二、关闭文件 打开的文件使用完成后一定要关闭,fstream提供了成员函数close()来完成此操作,如:file1.close();就把file1相连的文件关闭。 三、读写文件 读写文件分为文本文件和二进制文件的读取,对于文本文件的读取比较简单,用插入器和析取器就可以了;而对于二进制的读取就要复杂些,下要就详细的介绍这两种方式 1、文本文件的读写 文本文件的读写很简单:用插入器(<<)向文件输出;用析取器(>>)从文件输入。假设file1是以输入方式打开,file2以输出打开。示例如下: file2<<"I Love You";//向文件写入字符串"I Love You" int i; file1>>i;//从文件输入一个整数值。 这种方式还有一种简单的格式化能力,比如可以指定输出为16进制等等,具体的格式有以下一些 操纵符 功能 输入/输出 dec 格式化为十进制数值数据 输入和输出 endl 输出一个换行符并刷新此流 输出 ends 输出一个空字符 输出 hex 格式化为十六进制数值数据 输入和输出 oct 格式化为八进制数值数据 输入和输出 setpxecision(int p) 设置浮点数的精度位数 输出 比如要把123当作十六进制输出:file1<<hex<<123;要把3.1415926以5位精度输出:file1<<setpxecision(5)<<3.1415926。 2、二进制文件的读写 ①put() put()函数向流写入一个字符,其原型是ofstream &put(char ch),使用也比较简单,如file1.put('c');就是向流写一个字符'c'。 ②get() get()函数比较灵活,有3种常用的重载形式: 一种就是和put()对应的形式:ifstream &get(char &ch);功能是从流中读取一个字符,结果保存在引用ch中,如果到文件尾,返回空字符。如file2.get(x);表示从文件中读取一个字符,并把读取的字符保存在x中。 另一种重载形式的原型是: int get();这种形式是从流中返回一个字符,如果到达文件尾,返回EOF,如x=file2.get();和上例功能是一样的。 还有一种形式的原型是:ifstream &get(char *buf,int num,char delim='n');这种形式把字符读入由 buf 指向的数组,直到读入了 num 个字符或遇到了由 delim 指定的字符,如果没使用 delim 这个参数,将使用缺省值换行符'n'。例如: file2.get(str1,127,'A'); //从文件中读取字符到字符串str1,当遇到字符'A'或读取了127个字符时终止。 ③读写数据块 要读写二进制数据块,使用成员函数read()和write()成员函数,它们原型如下: read(unsigned char *buf,int num); write(const unsigned char *buf,int num); read()从文件中读取 num 个字符到 buf 指向的缓存中,如果在还未读入 num 个字符时就到了文件尾,可以用成员函数 int gcount();来取得实际读取的字符数;而 write() 从buf 指向的缓存写 num 个字符到文件中,值得注意的是缓存的类型是 unsigned char *,有时可能需要类型转换。 例: unsigned char str1[]="I Love You"; int n[5]; ifstream in("xxx.xxx"); ofstream out("yyy.yyy"); out.write(str1,strlen(str1));//把字符串str1全部写到yyy.yyy中 in.read((unsigned char*)n,sizeof(n));//从xxx.xxx中读取指定个整数,注意类型转换 in.close();out.close(); 四、检测EOF 成员函数eof()用来检测是否到达文件尾,如果到达文件尾返回非0值,否则返回0。原型是int eof(); 例: if(in.eof()) ShowMessage("已经到达文件尾!"); 五、文件定位 和C的文件操作方式不同的是,C I/O系统管理两个与一个文件相联系的指针。一个是读指针,它说明输入操作在文件中的位置;另一个是写指针,它下次写操作的位置。每次执行输入或输出时,相应的指针自动变化。所以,C 的文件定位分为读位置和写位置的定位,对应的成员函数是seekg()和seekp()。seekg()是设置读位置,seekp是设置写位置。它们最通用的形式如下: istream &seekg(streamoff offset,seek_dir origin); ostream &seekp(streamoff offset,seek_dir origin); streamoff定义于 iostream.h 中,定义有偏移量 offset 所能取得的最大值,seek_dir 表示移动的基准位置,是一个有以下值的枚举: ios::beg: 文件开头 ios::cur: 文件当前位置 ios::end: 文件结尾 这两个函数一般用于二进制文件,因为文本文件会因为系统对字符的解释而可能与预想的值不同。例: file1.seekg(1234,ios::cur); //把文件的读指针从当前位置向后移1234个字节 file2.seekp(1234,ios::beg); //把文件的写指针从文件开头向后移1234个字节 |
////////////////////////////////////////////////////
2009-11-15 11:18转自http://hi.baidu.com/bigbigrabbit/blog/item/9122d1a823337ff61e17a2ed.html
下面用三个例子说明: 一,写入数字 ofstream writefile("3.txt"); //定义对象,往文件写数据 if (writefile) //检查文件是否打开,如果打开则写数据 { writefile<<"0 1 2 3 4 5 6 7 8 9"; } ifstream readfile("3.txt"); //定义对象,读取数据 int date; for (int j=0; j<=9; j ) { readfile>>date; cout<<date<<endl; } 这里面用到了两个重要的操作符:<<和>>。<<是向文件中写入,>>从文件中读取。当然,写入操作和读取操作不能放在一起,如果放在一起就会读取不成功。 二,写入字符 ofstream writefile("3.txt"); char ch[]="woaini"; for (int i=0; i<strlen(ch); i ) { writefile.put(ch[i]); } ifstream readfile("3.txt"); char date; while (readfile.get(date)) //get之所以可以这样用,因为读到文件末尾就会返回false。 { cout<<date<<endl; } 这里用到两个方法:put和get。Put是写入单个字符,get是读取单个字符。当然上面的写入操作可以用<<进行,writefile<<”woaini”; 三,整行读写 ifstream readfile("1.txt"); ofstream writefile("2.txt"); const int len=200; char str[len]; while (readfile.getline(str,len)) { writefile<<str<<'n'; } 这个例子中,1.txt是一个已有文档,里面写满了文字,此程序是把1.txt中的内容写到2.txt中并且保存1.txt中格式不变。 整行读写中用到一个重要函数:getline,MSDN中的函数原型istream& getline(char* pch, int nCount, char delim='n');pch是字符数组,用来装读取的数据的;nCount是重要参数,指示一次读取长度;delim是以什么字符结尾,默认是’n’;也可是自己指定。 例子中有两个重要点,一是,len的选取,如果选取过于小,两个n之间的长度大于len,就会读取乱码,所以len尽量要大。二是,writefile<<str<<'n';中'n'是必须的,这是用来保证格式相同的。 |
相关文章推荐
- io - make c++ vector read/write from/to a file - Stack Overflow
- Configure file like format of ini and read data from ini file or write data to ini file
- C++ » File » File Read Write Screenshots
- How to read data from csv file in c#
- Read / Write Excel file in Java using Apache POI
- read UTF-8 text file in C++
- C++ - Read / Write std::map to a file
- Read a whole file into a string in C++
- [C++]C++小笔记之Simple File read and write-- ofstream and ifstream
- Spring Batch Read from DB and Write to File
- C++ IO: File Read Write
- protobuf read/write multiple messages from/to a file
- C++ Read Data from File into Struct
- The idcode read from the device does not match the idcode in the bsdl File.
- [Tips]:Read value from Resource file in C#
- download a file from a url in C++ - Ubuntu Forums
- Using CURL to download a remote file from a valid URL in c++
- How to get file extension from string in C++
- prjGetWriteINIFile - How to Read-Write INI file using VB & API - 读取/写入INI文件 - VB6 + API - SourceCode - HackerJLY
- C++ file read write