Method:
Copy Code code as follows:
Long filesize (char* filename);
char* file_get_contents (char* filename);
void file_put_contents (char* filename, char* data);
Example:
Copy Code code as follows:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Long filesize (char* filename);
char* file_get_contents (char* filename);
void file_put_contents (char* filename, char* data);
int main () {
printf ("%s\n", "----------------Begin---------------");
char* filename = "/tmp/tmp.txt";
File_put_contents (filename, "http://www.jb51.net");
char* data = file_get_contents (filename);
printf ("Fd::%s\n", data);
printf ("%s\n", "----------------End-----------------");
return 0;
}
Long filesize (char* filename) {
Long length;
file* stream = fopen (filename, "RB");
if (!stream) return 0L;
Fseek (Stream, 0L, seek_end);
Length = Ftell (stream);
Fclose (stream);
return length;
}
char* file_get_contents (char* filename) {
file* fp = fopen (filename, "RB");
if (!FP) {
printf ("%s\n", "The file can not be opened.");
Exit (0);
}
Long length = filesize (filename);
char* buffer = (char*) malloc (length);
Char buf[1024];
memset (buffer, 0x00, sizeof (buffer));
Fseek (FP, 0L, Seek_set);
while (Fgets (BUF, 1024, FP)!= NULL)
strcat (buffer, buf);
Fclose (FP);
return buffer;
}
void file_put_contents (char* filename, char* data) {
file* fp = fopen (filename, "w+");
if (!FP) {
printf ("The file can not be opened.\n");
Exit (1);
}
Fputs (data, FP);
Fclose (FP);
}