| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 1248 人关注过本帖
标题:请教读取指定行数据的问题!
只看楼主 加入收藏
minyangcau
Rank: 1
等 级:新手上路
帖 子:1
专家分:0
注 册:2009-8-26
结帖率:0
收藏
已结贴  问题点数:20 回复次数:1 
请教读取指定行数据的问题!
请教大家一个问题:
我的txt文件有大约3万多行,而我每次只需要其中的四行,这四行的行数知道,怎样才能直接读取指定行的数据。
现在的程序需要从第一行读到最后一行,太浪费时间了。
谢谢大家
搜索更多相关主题的帖子: 读数据 
2009-08-26 09:33
xufen340
Rank: 9Rank: 9Rank: 9
等 级:蜘蛛侠
帖 子:166
专家分:1351
注 册:2009-8-7
收藏
得分:20 
我写了一个,希望能帮到你。
#include <afx.h>
#include <afxwin.h>
#include <iostream>
using std::cout;
using std::endl;
CWinApp theApp;
int main(int argc, char *argv[])
{
   if (!AfxWinInit(GetModuleHandle(NULL), NULL, GetCommandLine(), 0))
   {
      cout << "panic: MFC couldn't initialize!" << endl;
      return 1;
   }

   CFile sourceFile;
   CFileException ex;
   /*
   打开文件。你可以用
   if (!sourceFile.Open(argv[1],
      CFile::modeRead | CFile::shareDenyWrite, &ex))
    我这里就直接read.dat,方便。
    */
   if (!sourceFile.Open("read.dat",                  
      CFile::modeRead | CFile::shareDenyWrite, &ex))
   {
      TCHAR szError[1024];
      ex.GetErrorMessage(szError, 1024);
      cout << "Couldn't open source file: ";
      cout << szError;
      return 1;
   }
   else
   {
      int line=0;       //行数
      int nposition=0;  //位置
      char pbuf[1];     //读取字符存放   
      while(line!=3){   
          //从头查找下一个字符
          sourceFile.Seek(nposition,CFile::begin);  
          //提取字符
          UINT nBytesRead = sourceFile.Read( pbuf, 1);
          //如果换行'\n',则行数加一
          if(pbuf[0]=='\n')
             line++;
          nposition++;
      }
     sourceFile.Seek(nposition,CFile::begin);  
     UINT nBytesRead = sourceFile.Read( pbuf, 1);
      //第四行字符的提取
     while(pbuf[0]!='\n'){
          sourceFile.Seek(nposition,CFile::begin);
          UINT nBytesRead = sourceFile.Read( pbuf, 1);
          cout<<pbuf[0];
          nposition++;
      }
      sourceFile.Close();
   }
   return 0;
}
2009-08-27 18:44
快速回复:请教读取指定行数据的问题!
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.011778 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved