使用c风格和c++风格逐行读取文件

发布于:2025-02-15 ⋅ 阅读:(15) ⋅ 点赞:(0)

使用c风格和c++风格逐行读取文件

c语言风格读取

#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void copentest(std::string filename)
{
    FILE *file = fopen(filename.c_str(), "r");
    if (!file)
    {
        perror("无法打开文件");
        return;
    }
    // 获取文件大小
    fseek(file, 0, SEEK_END);
    long fileSize = ftell(file);
    fseek(file, 0, SEEK_SET);
    // 分配内存以一次性读取整个文件
    char *buffer = (char *)malloc(fileSize + 1);
    if (!buffer)
    {
        perror("内存分配失败");
        fclose(file);
        return;
    }
    // 读取文件内容到内存
    fread(buffer, 1, fileSize, file);
    buffer[fileSize] = '\0'; // 确保字符串以 '\0' 结尾
    fclose(file);
    // 解析每一行
    char *line = strtok(buffer, "\n");
    while (line)
    {
        line = strtok(NULL, "\n");
        if(line)
            printf("==%s\n",line);
    }
    free(buffer);
}

int main()
{
    std::string filename = "test.txt";
    clock_t st, end;
    st = clock();
    copentest(filename);
    end = clock();
    double usedtime = (double)(end - st) / CLOCKS_PER_SEC;
    printf("used time:%lf\n",usedtime);
    return 0;
}

c++语言风格读取

#include <iostream>
#include <fstream>
#include <string>
#include <vector>

void iftest(std::string filename)
{
    std::ifstream file(filename); // 打开文件
    if (!file.is_open())
    {
        std::cerr << "无法打开文件" << std::endl;
        return;
    }
    std::vector<std::string> linevec;
    std::string line;
    while (std::getline(file, line))
    { // 从文件流中逐行读取
        linevec.push_back(line);
        // std::cout << line << std::endl; // 输出每行内容
    }
    std::cout<<"line num=="<<linevec.size()<<std::endl;
    file.close(); // 文件流离开作用域时也会自动关闭
}
int main()
{
    std::string filename = "test.txt";
    clock_t st, end;
    st = clock();
    iftest(filename);
    end = clock();
    double usedtime = (double)(end - st) / CLOCKS_PER_SEC;
    std::cout << "used :" << usedtime << std::endl;
    return 0;
}