- #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;
- }
读:从外部文件中将数据读到程序中来处理
对于程序来说,是从外部读入数据,因此定义输入流,即定义输入流对象: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<<message<<endl;
- }
- infile.close();
- }
对程序来说是将数据写出去,即数据离开程序,因此定义输出流对象ofstream outfile,outfile就是输出流对象,这个对象用来存放将要写到文件当中的数据。具体做法:
- ofstream outfile;
- outfile.open("myfile.bat"); //myfile.bat是存放数据的文件名
- if(outfile.is_open())
- {
- outfile<<message<<endl; //message是程序中处理的数据
- outfile.close();
- }
- else
- {
- cout<<"不能打开文件!"<<endl;
- }