· C++ 文本操作大全
>>> 快速读取 txt 文档的行数
#include <sys/stat.h>
int getTxtLineCount(std::string file_name){
int line_count = 0;
struct stat s;
stat(file_name.c_str(), &s);
std::string file_buf(s.st_size + 1, '\0');
FILE* fp = fopen(file_name.c_str(), "rb");
fread(&file_buf[0], sizeof(char), file_buf.size(), fp);
const char* file_buf_tmp = file_buf.c_str();
while (*file_buf_tmp != '\0')
{
const char* p = strchr(file_buf_tmp, '\n');
if (p == NULL)
{
++line_count;
break;
}
line_count += p - file_buf_tmp > 0;
file_buf_tmp += p - file_buf_tmp + 1;
}
return line_count;
}
>>> 一次性将 txt 读到 string / 一次性将 string 写到 txt
#include <fstream>
#include <iostream>
/*
*@brief Read the whole txt content to string in a short time
*@brief Write the whole string to txt in a short time
*/
std::ifstream ifs("C:123.txt");
std::istreambuf_iterator<char> begin(ifs);
std::istreambuf_iterator<char> end;
std::string str(begin, end);
ifs.close();
std::ofstream ofs("C:/456.txt");
ofs << str;
ofs.close();
>>> 特定标志分割字符串
#include <fstream>
#include <vector>
#include <iostream>
void split(std::string &str, std::vector<std::string> & result, std::string pattern)
{
std::string::size_type pos;
str += pattern;
int size = str.size();
for (int i = 0; i < size; i++)
{
pos = str.find(pattern, i);
if (pos < size)
{
std::string s = str.substr(i, pos - i);
result.push_back(s);
i = pos + pattern.size() - 1;
}
}
}
>>> 按行分割string后按空格提取内容
std::string some_str;
std::string::size_type pos = 0;
std::vector<std::string> vec;
std::string str;
while ((pos = some_str.find_first_of('\n')) != std::string::npos){
str = some_str.substr(0, pos);
if (str != ""){
split(str, vec, " ");
for(auto it = vec.begin(); it != vec.end(); it++)
std::cout << *it << std::endl;
}
some_str= some_str.substr(pos + 1, some_str.length() - str.length());
pos = 0;
vec.clear();
}
>>> ifstream 读取坐标数据
#include <fstream>
#include <iomanip>
std::ifstream ifs("C:/123.txt");
if(!ifs)
return;
while(!ifs.eof()){
if(ifs.peek() == '\n'){
ifs.ignore();
if(ifs.peek() == '\n')
break;
}
ifs >> x >> y >> z;
std::cout << setprecision(7) << x << " " << y <<" " << z << std::endl;
}
ifs.close();
>>> 读 .csv 文件
FILE *fp = NULL;
char *line,*record;
char buffer[1024];
if ((fp = fopen("Student.csv", "at+")) != NULL)
{
fseek(fp, 170L, SEEK_SET);
char delims[] = ",";
char *result = NULL;
int j = 0;
while ((line = fgets(buffer, sizeof(buffer), fp))!=NULL)
{
record = strtok(line, ",");
while (record != NULL)
{
if (strcmp(record, "Ps:") == 0)
return 0;
printf("%s ", record);
if (j == 10)
break;
record = strtok(NULL, ",");
j++;
}
printf("\n");
j = 0;
}
close(fp);
fp = NULL;
}
>>> 写 .csv 文件
float x, y
std::ofstream ofs("C:/123.csv")
ofs << x << "," << y << "\n"
ofs.close()
>>> else