在C++中,如何读取一个txt文件,或向txt文件中写入数据 ?

如题所述

一、写入文件
#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();//关闭文件
}

二、读取文件
上面仅仅是将文本写入文件,并没有读取出来。
以下为读取文件的一种方法:将文件每行内容存储到字符串中,再输出字符串
#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()
是用来读取回车键的,如果没这一行,输出的结果一闪就消失了
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2020-04-30
一、写入文件
#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();//关闭文件
}
二、读取文件
上面仅仅是将文本写入文件,并没有读取出来。
以下为读取文件的一种方法:将文件每行内容存储到字符串中,再输出字符串
#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()
是用来读取回车键的,如果没这一行,输出的结果一闪就消失了
}
相似回答