#include <iostream>
#include <vector>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <fstream>
#include <sys/types.h>
#include <regex.h>
#include <string>
using namespace std;
bool readFileToString(string file_name, string& fileData)
{
ifstream file(file_name.c_str(), std::ifstream::binary);
if(file)
{
// Calculate the file's size, and allocate a buffer of that size.
file.seekg(0, file.end);
const int file_size = file.tellg();
char* file_buf = new char [file_size+1];
//make sure the end tag \0 of string.
memset(file_buf, 0, file_size+1);
// Read the entire file into the buffer.
file.seekg(0, ios::beg);
file.read(file_buf, file_size);
if(file)
{
fileData.append(file_buf);
}
else
{
std::cout << "error: only " << file.gcount() << " could be read";
fileData.append(file_buf);
return false;
}
file.close();
delete []file_buf;
}
else
{
return false;
}
}
int main()
{
string data;
if(readFileToString("./S9306.sample", data))
{
cout<<"File data is:\r\n"<<data<<endl;
}
else
{
cout<<"Failed to open the file, please check the file path."<<endl;
}
}
单元测试1-读出文件里面的内容
最新推荐文章于 2024-01-18 11:43:27 发布