您的位置:首页 > 编程语言 > C语言/C++

C++读取txt文件的方法

2011-10-27 18:06 691 查看
// win32console.cpp : 定义控制台应用程序的入口点。
//C++读取txt文件的方法

#include "stdafx.h"

#include <fstream>
#include <iostream>

using namespace std;

typedef struct node{
int data;
struct node *next;
} node;

node *creat(ifstream &ifp)
{
node *h=NULL,*p=NULL,*q=NULL;
int data;
while (ifp>>data)
{
p=new node;
p->data=data;
p->next=NULL;
if (!h) h=p;
else  q->next=p;
q=p;
}
return h;
}
void prt(node *h)
{
if (h)
{
cout<<h->data<<endl;
prt(h->next);
}
}

int _tmain(int argc, _TCHAR* argv[])
{
//--file1 open
ifstream fp("d:\\data.txt",ifstream::in);
node *hst=creat(fp);
fp.close();
prt(hst);
//--file2 open
ifstream r("d:\\test.txt",ifstream::in);
if(!r)
{
cout<<"打开文件出错!"<<endl;
}
else
{
char line[4000];   //[100]2000
while(r>>line)
{
cout<<line<<endl;
}
r.close();
}
//stop screen
char q;
cin>>q;
return 0;
}

//---------------------------------------------------------------------------
//d:\\data.txt 内容
//1 2 3 4 5 6
//7 8 9 10 11 12
//100998877
//55 56 57   58 59 60

//d:\\test.txt 内容
//姓名:hehe年龄:12备注:123
//姓名:haihai年龄:18备注:12ff
//姓名:aa年龄:22备注:ff11
//objectarx 文件处理方法
//使用纯c++来处理文本文件,可以使用ifstream、ofstream以及iofstream,
//在arx中由于强制使用unicode,应该使用arx提供的AcFStream
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: