精品文档
精品文档
c++
对
txt
文件的读取与写入
/*
这是自己写程序时突然用到这方面的技术,
在网上
搜了一下,特存此以备后用
~
*/
#include
#include
#include
using namespace std;
i
nt main(){
char buffer[256];
ifstream myfile ("c:\\a.txt");
ofstream outfile("c:\\b.txt");
if(!myfile){
cout << "Unable to open myfile";
exit(1); // terminate with error
}
if(!outfile){
cout << "Unable to open otfile";
exit(1);
//
terminate
with
error
}
int
a,b;
int
i=0,j=0;
int
data[6][2];
while
(!
myfile.eof()
)
{
myfile.getline
(buffer,10);
sscanf(buffer,"%d
%d",&a,&b);
cout<
"<
data[i][0]=a;
data[i][1]=b;
i++;
}
myfile.close();
for(int k=0;k
outfile<
tob_id_3208
cout<
}
outfile.close(); return 0; }
无论读
写都要包含
头文件
读:从外部文件中将数据读到程序中来处理
对于程序来说,
是从外部读入数据,因此定义输入流,即定义输入流对象
:ifsteam infile
,
infile
就是输入流对
象。
这个对象当中存放即将从文件读入的数据流。假设有名字为
myfile.txt
的文件,存有
两行数字数据,
具体方法:
int a,b;
ifstream infile;
infile.open("myfile.txt");
//
注意文
件
的
路
径
infile>>a>>b;
//
两
行
数
据
可以
连
续读出
到
变
量里
infile.close()
如果是个很大的多行存储的文本型文件可以这么读:
char
buf[1024];
//
临时保存读取出来的文件内容
string
message;
ifstream
infile;
infile.open("myfile.js");
if(infile.is_open())
//
文件打开成功
,
说明曾经写入过东西
{
while(infile.good()
&&
!infile.eof())
{
memset(buf,0,1024);
infile.getline(buf,1204);
message
=
buf;
......
//
这
里
可
能
对
message
做
一
些
操
作
cout<
infile.close(); }
写:将程序中处理后的数据写到文件当中
对程序
来说是将数据写出去,即数据离开程序,因此定义输出流对象
ofstream outfile
,
outfile
就是
输出流对象,这个对象用来存放将要写到文件当中的数据。具体做法:
ofstream outfile;
outfile.open("myfile.bat");
//myfile.bat
是
存
放
数
据
的
文
件
名
if(outfile.is_open())
{
outfile<
//message
是程序中处理的数据
outfile.close();
}
else
{
cout<<"
不能打开文件
!"<
c++
对文件的读写操作的例子
/*/
从键盘读入一
行字符,把其中的字母依次放在磁盘文件
fa2.dat
中,再把它从磁盘文件读入程序,
将其
中
的
小
写
字
母
改
成
大
写
字
母
,
再
存
入
磁
盘
fa3.dat
中
*/
#
i
nclude
#
i
nclude
#
i
nclude
using
namespace
std;
//
从键盘上读取字符
的函数
void
read_save(){
char
c[80];
ofstream
outfile("f1.dat");//
以输出方工
打开文件
if(!outfile){
cerr<<"open
error!"<
注意是用的
是
cerr
exit(1);
}
cin.getline(c,80);//
从键盘读入一行字符
for(int i=0;c[i]!=0;i++) //
对字符一个一个的处理,
直到遇到
'/0'
为止
if(c[i]>=65&&c[i]<=90||c[i]>=97&&c[i]<=122){//
保证输入的字符