C++ 读、写、改、删除本地文件内容 |
您所在的位置:网站首页 › 记事本如何批量删除数据和文字内容 › C++ 读、写、改、删除本地文件内容 |
在写程序的过程中,有时候需要对程序中的一些参数或者变量在本地读取、存储以及修改等,因此掌握一下C++对于本地文件的一些操作还是挺有必要的。 1、读取本地文件:C++对于本地文件的读取以及写入都还是挺简单的,主要采用了数据流的形式,读取上来的是一个个行排列的字符串,后面根据自己的需要进行详细的区分,例如字符串转数字、字符串分割等。一个简单的字符串读取函数大概可以写成这个样子: void local_file_process::ReadLoaclFile() { ifstream fin; string file_path = "xxx"; fin.open(file_path.c_str()); string linestr; if(fin.is_open())//确认文本存在,is_open()用于确认该文本是否打开 { while (getline(fin, linestr))//行遍历 { //在这里进行你需要的数据处理 } } else{ ROS_ERROR("can not find locat file,check file path"); } fin.close(); }这里需要注意的是最好添加一下fin.is_open()判断,因为如果没有这个判断,即使你的路径是不正确的,但是它不会报错,只会读不到东西,这样子可能会导致后面的整个处理都错误。 第二个问题是这里关于打开路径的问题,上面我写成了: string file_path = "xxx"; fin.open(file_path.c_str());其实这里可以直接写成: fin.open("xxx");但是注意到有时候我们可能处理本地文件的地方不止一个地方,所以如果直接写死的话后面要改起来会比较麻烦还容易漏掉,所以最好的方式是用一个全局变量,这样子我们只要改一个地方就可以了,保证了代码的稳定性以及便捷性。但是这里为什么没有写成: string file_path = "xxx"; fin.open(file_path);这样子呢? 这里是由于引用的open函数的问题,open函数传参为open(const char* filepath),如果直接给string类型编译不会报错但是运行时是无法找到地址的。可以写成这样子: const char* s; s = file_path.c_str(); fin.open(s); 或者 fin.open(file_path.c_str()); c_str()生成一个const char *指针,指向字符串的首地址但是一定不能直接给字符串。虽然直接给定地址的情况看起来确实很像是传入了一个字符串。 2、写本地文件:写的方式与读的方式大体类似,具体看参考代码即可: void local_file_process::AddLoaclFile(vector msg) { //写入到文本最后面 std::ofstream out(file_path.c_str(),std::ios::app); int len = msg.size(); for(int i=0;i ifstream fin; fin.open(file_path.c_str()); string linestr; string strFileData = "";//暂存新的数据的地方 int file_line = 0; int line = 1; int line_2 = 1; //查找需要修改的id是哪一个 while (getline(fin, linestr)) { file_line ++; if(linestr == msg[1]) break; line++; } fin.close(); //如果id存在,这里应相等 if(file_line != line) {//如果说目前的库位信息中没有这个id信息,新增一个新的库位信息 AddLoaclStorage(msg); return; } ifstream in; in.open(file_path.c_str()); //将需要修改的四行内容保存为新的msg。其他的行不变,暂存到strFileData while (getline(in, linestr)) { if(line_2 == line-1) { strFileData += msg[0]; strFileData += "\n"; } else if(line_2 == line) { strFileData += msg[1]; strFileData += "\n"; } else if(line_2 == line+1) { strFileData += msg[2]; strFileData += "\n"; } else if(line_2 == line+2) { strFileData += msg[3]; strFileData += "\n"; } else { strFileData += linestr; strFileData += "\n"; } line_2++; } in.close(); ofstream out; out.open(file_path.c_str()); out.flush();//清空file内容 out file_line++; if(linestr == msg) break; line++; } fin.close(); if(file_line != line) { cout line_2++; continue; } else if(line_2 == line) { line_2++; continue; } else if(line_2 == line+1) { line_2++; continue; } else if(line_2 == line+2) { line_2++; continue; } else if(line_2 == line+3) { line_2++; continue; } else { strFileData += linestr; strFileData += "\n"; } line_2++; } in.close(); ofstream out; out.open(file_path.c_str()); out.flush(); out //如果有该字符 } |
今日新闻 |
点击排行 |
|
推荐新闻 |
图片新闻 |
|
专题文章 |
CopyRight 2018-2019 实验室设备网 版权所有 win10的实时保护怎么永久关闭 |