C++文本读取和写入

  1. #include <fstream>  
  2. ofstream         //文件写操作 内存写入存储设备   
  3. ifstream         //文件读操作,存储设备读区到内存中  
  4. fstream          //读写操作,对打开的文件可进行读写操作 

这个是写入

void SaveReuslt(char* pathName,std::vector <double> result,int setnum)
{
    FILE *p_file = fopen(pathName, "a");
    fprintf(p_file, "*************************************\n");
    fprintf(p_file, "%d: H: %lf W: %lf L: %lf \n",setnum,result[0],result[1],result[2]);
    fclose(p_file);
    p_file=NULL;
}

这个是读取

ofstream和ifstream只能进行读或是写,而fstream则同时提供读写的功能。

读取:name是文件的路径

std::string Readtxt(std::string name) {

std::fstream file;

file.open(name);

std::string content;

while (!file.eof()) { file.eof()指的文件的结束符,也就是最后一个字符的下一位

file>> content;

std::cout << content << std::endl;

}

file.close();//关闭是个好习惯

return content;

}

这各读写都是用在项目里的,用没问题,以后有时间再做详细的总结

猜你喜欢

转载自blog.csdn.net/qq_31638535/article/details/82588496