首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

C++中文件操作和内存管理的有关问题

2012-03-03 
C++中文件操作和内存管理的问题#includeiostream#includefstreamusingnamespacestd//该程序已知有两

C++中文件操作和内存管理的问题
#include   <iostream>
#include   <fstream>
using   namespace   std;

//该程序已知有两个问题,可是我一时无从下手,请各位帮帮忙吧,谢谢了。
//1   文件读取
//2   内存空间分配
//数据文件另附上
void   main()
{
char   filename[]= "F:\\exchanges.txt ";
char   buffer[255];

//希望将文件中的内容读入到数据content中,
//类似于Java中的char[][]   content
//数据类似于:
//amex
//ase
//asx
//...
//都是字符串
//但是到底有几个不知道
char**   content;

//首先求出行数line
ifstream   in;
in.open(filename);
if(!in){
cerr < < "Can 't   open   file! " < <endl;
exit(1);
}
int   line=0;
while(in.getline(buffer,255)){
line++;
}
cout < < "Line   :   " < <line < <endl;
//已经关闭了文件输入流!!!
in.close();
//line==39

{
//将数据存入到数组中去
content=new   char*   [line];
ifstream   in;
in.open(filename);
//为什么此时无法打开文件??????
//即使换成其他的文件,例如 "username.txt ",仍然无法打开
//但是如果另外再使用一个ifstream就可以读取数据了?
if(!in){
cerr < < "Can 't   open   file! " < <endl;

//此时文件流的状态为:eof和fail
if(in.eof())cerr < < "Eof " < <endl;
if(in.fail())cerr < < "Fail " < <endl;
if(in.bad())cerr < < "Bad " < <endl;

delete[]   content;
exit(1);
}
int   i=0;
while(in.getline(buffer,255)){
content[i]=new   char[255];
strcpy(content[i],buffer);
cout < <content[i] < <endl;
}
}

//收尾工作
//出现问题了:
//delete[]   content[i];   指针不是数组,错误!
//但是如何更正,或者是用更好的数据结构来实现呢?
for(int   i=0;i <line;i++){
delete[]   content[i];
}
delete[]   content;
}

[解决办法]
费那事干嘛?直接用vectot <string> 不就完了么
vector <string> list;
ifstream i( "xx ");
while(in.getline(buffer,255)){
string line=buffer;
list.push_back(line);
}

热点排行