C/C++ 文件读写操作
?
标准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) { fclose(fp); 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;}