vety-language/utils/file.c

68 lines
1.5 KiB
C

//
// Created by Natuie on 2025/3/22.
//
#include <stdio.h>
#include <malloc.h>
#include <stdbool.h>
#include <string.h>
#include "file.h"
// 读取文件
char* read_file(const char* filename) {
FILE* file = fopen(filename, "r");
if (!file) {
fprintf(stderr, "Failed to read file: %s\n", filename);
return NULL;
}
// 获取文件大小
fseek(file, 0, SEEK_END);
long file_size = ftell(file);
rewind(file);
// 分配内存
char* buffer = (char*)malloc(file_size + 1);
if (!buffer) {
fprintf(stderr, "内存分配失败\n");
fclose(file);
return NULL;
}
// 读取文件内容
size_t read_size = fread(buffer, 1, file_size, file);
buffer[read_size] = '\0'; // 添加字符串结束符
fclose(file);
return buffer;
}
// 文件是否存在
bool file_exists(const char* filename) {
FILE* file = fopen(filename, "r");
if (file) {
fclose(file);
return true;
}
return false;
}
// 构建目录
// 处理'./'与'../'还有'/'等目录相加
char* build_path(const char* path1, const char* path2) {
size_t len1 = strlen(path1);
size_t len2 = strlen(path2);
char* result = (char*)malloc(len1 + len2 + 2); // 加上可能的'/'和'\0'
if (!result) {
fprintf(stderr, "内存分配失败\n");
return NULL;
}
strcpy(result, path1);
if (path1[len1 - 1] != '/') {
strcat(result, "/");
}
strcat(result, path2);
return result;
}