2010-10-07

[C/C++語言] file_put_contents() 與 file_get_contents()

Base C library :
#include <stdio.h>
#include <malloc.h>

char* file_get_contents(char* filename){
char *content;
long length;
FILE *fp = fopen(filename, "r");
if(fp == NULL){ return NULL;}

fseek(fp, 0, SEEK_END);
length = ftell(fp);

content = (char*)malloc(length + 1);

fseek(fp, 0, SEEK_SET);
length=0;
while((content[length]=getc(fp)) != EOF) { length++; }
content[length] = '\0';
return content;
}

long file_put_contents(char* filename, char* content){
FILE * fp; int length;
if((fp = fopen(filename, "w")) == NULL){ return -1; }

fputs(content, fp);
fclose(fp);
return length;
}


int main(){
file_put_contents("temp.txt","hello,world! for C \n");
char * contents = file_get_contents("temp.txt");
printf("%s",contents);

return 0;
}



Base C++ library :
#include <fstream>
#include <string>

#include <iostream>
using namespace std;


string file_get_contents(char* fileName) {
ifstream file(fileName);
if (!file) { return ""; }

string content = "", line;
while (!file.eof()){
getline(file,line);
content += line+"\n";
}
file.close();
return content;
}

void file_put_contents(char * fileName, char * content) {
ofstream file;
file.open(fileName);
file << content;
file.close();
}


int main() {
file_put_contents("temp.txt", "hello,world! for C++ \n");
cout << file_get_contents("temp.txt");

return 0;
}


參考來源:
【原创】纯C 实现PHP函数 file_get_contents() file_put_contents()。。。支持远程URL
c++ 版的file_put_contents()和file_get_contents()
[C++]Otwarcie pliku

0 回應: