C++ 文本操作大全

· C++ 文本操作大全

>>> 快速读取 txt 文档的行数

#include <sys/stat.h>

/*
*@brief Read the file of txt's linecount
*@paras file_name (the source path of file)
*/

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)
        {
            ///最后一行没有'\n'
            ++line_count;
            break;
        }
        ///过滤空行
        line_count += p - file_buf_tmp > 0;
        ///查找下一个'\n'
        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>

/*
*@brief Split the string to vector based on specific pattern
*
*@paras str (the string to be split)
*@paras result (split result)
*@paras str (split pattern)
*
*/

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 != ""){  // Ignore blank lines
        split(str, vec, " ");   // the pattern is " "(balnk)
        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'){  // the loop exits if the line without data
        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);  //定位到第二行,每个英文字符大小为1
    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)//当读取到Ps那一行时,不再继续读取
                return 0;
            printf("%s ", record);//将读取到的每一个数据打印出来
            if (j == 10)  //只需读取前9列
                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

猜你喜欢

转载自blog.csdn.net/qq_34719188/article/details/81112636