#import <sys/stat.h>
// 判断文件是否存在
bool file_exists(const char *filename){
return access(filename, 0) == 0;
}
//获取文件大小方法1
long file_size(const char *file){
long length = -1;
FILE *fp = fopen(file, "rb+");
if (fp == NULL) {
return length;
}
fseek(fp, 0, SEEK_END);
length = ftell(fp);
fclose(fp);
return length;
}
//获取文件大小方法2
long get_file_size(const char *file){
long length = -1;
struct stat statbuff;
if(stat(file, &statbuff) < 0){
return length;
}else{
length = statbuff.st_size;
}
return length;
}
//字符串连接
char *str_cat(char *str, char *str2){
long len = strlen(str) + strlen(str2);
char *s = (char *)malloc(sizeof(char) * len);
strcpy(s, str);
strcat(s, str2);
return s;
}
//文件读取
char *file_get_contents(const char *filename){
FILE *fp;
size_t size = 1024, n = 0, count = 0, sz = sizeof(char);
char *data = (char *)malloc(sizeof(char) * size);
if(file_exists(filename)){
fp = fopen(filename, "r+");
if(fp){
do{
if(count > 0){
data = realloc(data, (size + count) * sz);
}
n = fread(data + count, sz, size, fp);
if(n < 0){
free(data);
data = NULL;
}
count += n;
}while(n > 0);
fclose(fp);
if(data){
if (0 == (count + sz) % 512){//几率很小的溢出
data = realloc(data, count + sz);
}
data[count] = '\0';
}
return data;
}
}
return NULL;
}