1、C(高效、字符数量不会增加)
(1)、读文件
第一种:
static bool open(const string filename, string& content) //filename:文件名 content:内容
{
FILE *file = fopen(filename.c_str(), "rb"); //只读打开一个二进制文件,只允许读数据
if (file == NULL)
return false;
fseek(file, 0, SEEK_END); //设置文件指针(文件头0(SEEK_SET),当前位置1(SEEK_CUR),文件尾2(SEEK_END))
int len = ftell(file); //偏移长度
rewind(file);
char *buffer = new char[len];
fread(buffer, sizeof(char), len, file);
content.assign(buffer, len);
delete []buffer;
fclose(file);
return true;
}
第二种:
static bool open(const string filename, string& content) //filename:文件名 content:内容
{
FILE *file = fopen(filename.c_str(), "rb"); //只读打开一个二进制文件,只允许读数据
if (file == NULL)
return false;
fseek(file, 0, SEEK_END); //设置文件指针(文件头0(SEEK_SET),当前位置1(SEEK_CUR),文件尾2(SEEK_END))
int len = ftell(file); //偏移长度
rewind(file);
char *buffer = new char[len];
fread(buffer, sizeof(char), len, file);
content.assign(buffer, len);
delete []buffer;
fclose(file);
return true;
}
2、C++(高效不会引入新的字符)
(1)、读文件
static open(const std::string filename, std::string& content)
{
ifstream in(filename.c_str(), ios::in);
istreambuf_iterator<char> beg(in), end;
string content(beg, end);
in.close();
}
(2)、写文件
static write(const std::string filename, std::string& content){ ofstream fileStream("filename",ios::binary | ios::out); fileStream.write(strContent.c_str(),strContent.size()); fileStream.close();}
第三种 QT方法(会引入新的字符、但是效率非常高)
(1)、读文件static open(QString filename, QString &content)
{
if(!filename.open(QIODevice::ReadOnly | QIODevice::Text))
{
return;
}
QTextStream txtInput(&filename);
while(!txtInput.atEnd())
{
content = txtInput.readLine();
}
file.close();
}
(2)写文件static write(QString filename, QString &content)
{
QFile file(filename);
if (file.open(QFile::Append | QFile::Text))
{
QTextStream out(&file);
out << content;
out.flush();
file.close();
}
}