我有很多用fprintf写入的文本文件,文件以\n换行,每个文件的行数也不定,每行中的各数据用“,”隔开,现在的问题是,怎样把文件中的某一行(由用户任意指定)读出来,并把此行中的各数据再赋给变量?
还有就是如何得到文件的行数?
谢谢各位了!

解决方案 »

  1.   

    将文件读入内存,然后统计\n就可以得到行数了
    相应的,取用户指定的行的前一个\n到后一个\n之间的数据就可以读出
    用户指定的行了
      

  2.   

    我还是不大明白,如何统计呢?取出该行的数据又怎么办呢?是把它存入字符串str然后用str.Mid()分别取出数据吗?
    我的水平不行,能给点代码吗?
    我第一次到这里来,我怎么没有找到给分的地方?
      

  3.   

    你的想法很不错啊,可行!
    不过有个函数fgets()可以一次读一行,循环读N行就可以了,呵呵
      

  4.   

    CStdioFile的ReadString  WriteString  以下是一位大侠给我的代码,遇到=号及把=后面的数值加100void CReplaceFileView::OnModifyText() 
    {
    // TODO: Add your command handler code here
      CStdioFile file_src;
      CStringArray strArray;
      file_src.Open("data.txt",CFile::modeRead|CFile::typeText);
      CString strTemp;
      CString strTemp2;
      int index=0;
      while(file_src.ReadString(strTemp))
      {
    strArray.Add(strTemp);
    index++;
      }
      
      file_src.Close();
      
      file_src.Open("data.txt",CFile::modeWrite|CFile::typeText|CFile::modeCreate);
     for( int i=0;i<index;i++)
      {
    strTemp=strArray[i];
    int position=strTemp.Find('=')+1;
    strTemp2=strTemp.Left(position); strTemp.Delete(0,position);
    int tempData = atoi((LPTSTR)(LPCTSTR)strTemp);
    tempData+=100;//将数据增加100;
    strTemp.Format("%d\n",tempData);
    strTemp2+=strTemp;
    file_src.WriteString(strTemp2);  }
      
      file_src.Close();
    }
    ------
    file:data.txt
    -----------
    set a=1809
    set b=123
    set c=586
    set d=458
    set e=1234
    set f=4567
      

  5.   

    你的文件是用fprintf,读的时候你可以用流来读,
    ifstream from("filename.txt") ;
    string str ;
    getline( from , str ) ;
    就读出了一行,getline运行几次就读到了第几行。
      

  6.   

    读出来的str中的数据给其他变量你可以用istringstream来做。
    比如读出来的是 "1 2 3"
    istringstream iss( str ) ;
    int x , y , z ;
    iss >> x >> y >> z ;
    之后,x,y,z就是1,2,3了