读取文本文件
#include <iostream> #include <stdlib.h> #include <unistd.h> #include <fstream> using namespace std; void dofile(char *filename) { FILE *f;long len;char *data; f=fopen(filename,"rb"); fseek(f,0,SEEK_END); len=ftell(f); fseek(f,0,SEEK_SET); data=(char*)malloc(len+1); fread(data,1,len,f); fclose(f); cout << data << endl; free(data); } void dofile2(char *filename) { ifstream input(filename); if(!input){ cout << "open file error" << endl; } #if 1 string s; string str; while(input >> s) str += s; cout << str << endl; #else char buf[1024]; char c; int n = 0; while(input >> c){ sprintf(buf+n,"%c",c); ++n; } cout << buf << endl; #endif } int main() { cout << "Hello World!" << endl; // dofile("./test1.txt"); // dofile2("./test1.txt"); // dofile("./test2.json"); // dofile2("./test2.json"); // dofile2("./test3.json"); dofile2("./test4"); return 0; }