标准C++ 读写文件内容:
//标准C++ 读文件内容 ( 仿PHP ) 2012-8-12 by Dewei
//用法:string s = file_get_contents("C:\\LICENSE.txt");
string file_get_contents(const string &filename)
{
string contents = "";
fstream in;
in.open(filename.c_str(), fstream::in|fstream::binary|fstream::ate);
if (in.good()) {
fstream::pos_type end_pos = in.tellg();
long num_size = end_pos;
++num_size;
in.seekg (0, fstream::beg);
char *buffer = new char[num_size];
memset(buffer, 0, num_size);
in.read(buffer, end_pos);
in.close();
contents = buffer;
if (buffer != NULL)
delete[] buffer;
}
return contents;
}
//标准C++ 写入文件内容 ( 仿PHP ) 2012-8-12 by Dewei
//用法:file_put_contents("C:\\LICENSE.txt", "写入内容");
bool file_put_contents(const string &filename, const string contents)
{
fstream out;
out.open(filename.c_str(), fstream::out|fstream::binary);
if (out.good()) {
out.write(contents.c_str(), contents.length());
out.close();
}
return true;
}
C 语言实现 读写文件内容:
//C 语言实现 读取文件内容 ( 仿PHP ) 2012-6-25 by Dewei
//用法:string s = file_get_contents("C:\\LICENSE.txt");
string file_get_contents(const string &filename)
{
string contents;
FILE *fp;
fp = fopen(filename.c_str() , "rb");
if (fp == NULL) {
return "";
}
fseek(fp, 0, SEEK_END);
int file_size = ftell(fp);
char *tmp;
fseek(fp, 0, SEEK_SET);
tmp = (char *)malloc(file_size+1);
memset(tmp, 0, file_size+1);
fread(tmp, sizeof(char), file_size, fp);
if (ferror(fp)) {
/* now, it is an error on fp */
}
fclose(fp);
contents = tmp;
free(tmp);
return contents;
}
//C 语言实现 写入文件内容 ( 仿PHP ) 2012-6-25 by Dewei
//用法:file_put_contents("C:\\LICENSE.txt", "写入内容");
bool file_put_contents(const string &filename, const string contents)
{
FILE *fp;
fp = fopen(filename.c_str() , "wb");
if (fp == NULL) {
return false;
}
fwrite(contents.c_str(), contents.length(), 1, fp);
fclose(fp);
return true;
}
1922

被折叠的 条评论
为什么被折叠?



