c++ 读写txt方法

写:

#include<fstream>

std::ofstream fout;
 fout.open("output.txt"); 
 fout <<"test content";

 

读:

FILE *fp=NULL;
   //得到csv文件中所有的字符
   fp = fopen("C:\\UDS\\config\\input.txt","rb");
   char c = fgetc(fp);
   char* fp_base = fp->_base;

//通过换行符分割成一个数组
 char* vectLines=strtok(const_cast<char*>( fp_base.GetText()), "\n");
 while( vectLines != NULL ) 
 { 
  vectLines = strtok( NULL, "\n"); 
 }

  fclose(fp);

注意这个读文件的方法有个缺点:文件大小有限制,貌似是4000多个字符,可以通过以下方法去解决:

FILE *fp=NULL;
   fp = fopen("input.txt","rb");
   char c = fgetc(fp);

while("判断c是有效字符")

{

//将读到的字符写入一个数组

}
   char* fp_base = fp->_base;

//通过换行符分割成一个数组
 char* vectLines=strtok(const_cast<char*>( fp_base.GetText()), "\n");
 while( vectLines != NULL ) 
 { 
  vectLines = strtok( NULL, "\n"); 
 }

  fclose(fp);

 

#include <fstream>  

#include <string>  

#include <iostream>  

using namespace std;  

  

int main()  

{  

    ifstream in("1.txt");  

    string filename;  

    string line;  

  

    if(in) // 有该文件  

    {  

        while (getline (in, line)) // line中不包括每行的换行符  

        {   

            cout << line << endl;  

        }  

    }  

    else // 没有该文件  

    {  

        cout <<"no such file" << endl;  

    }  

  

    return 0;  

}  

 

 

 

 

posted on 2014-02-18 11:38  程序员乌鸦  阅读(809)  评论(0编辑  收藏  举报

导航