作为C++风格的文件读取方式
可以使用文件流类——fstream类
fstream类有两种子类
分别是用于读出文件的ifstream类
以及用于写入文件ofstream类
在使用是应加入引用 : #include <fstream>
注意该头文件使用std命名空间
还应该加入语句 :using namespace std;
使用的使用应该创建一个文件流对象
比如读入一个文件可以使用下列语句:
ifstream File;
char *FileName;
char DataBuffer[128];
/* 此处应设定文件名 */
File.open(FileName); //打开文件
//open函数其实有三个参数,此处后两个使用默认值了,具体函数使用请见MSDN
if(File)
{ //文件打开成功
// 此处加入对文件内容的处理
while(!File.eof())
{ //循环读入数据
File.read(DataBuffer,128);
/*对缓冲区中的读入数据进行操作*/
}
}
else
{ //文件打开失败
/*进行错误处理*/
}
File.close(); //关闭文件
与上述代码类似
将内容写入文件需要创建一个ofstream对象
可以多看看MDSN
可以参考CPP标准函数库
C++读取文件txt,循环逐行输出
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
int 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<<a<<" "<<b<<endl;
data[i][0]=a;
data[i][1]=b;
i++;
}
myfile.close();
for(int k=0;k<i;k++){
outfile<<data[k][0] <<" "<<data[k][1]<<endl;
cout<<data[k][0] <<" "<<data[k][1]<<endl;
}
outfile.close();
return 0;
}
C++如何实现读取文件数据
最新推荐文章于 2024-03-12 10:02:26 发布