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';
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 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;
}