c說話文件讀寫示例(c說話文件操作)。本站提示廣大學習愛好者:(c說話文件讀寫示例(c說話文件操作))文章只能為提供參考,不一定能成為您想要的結果。以下是c說話文件讀寫示例(c說話文件操作)正文
辦法:
long filesize(char* filename);
char* file_get_contents(char* filename);
void file_put_contents(char* filename, char* data);
示例:
#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);
}