Prepare Build and Testing executable binary / Prepare-Build-Testing-With-Make (push) Successful in 9s
Prepare Build and Testing executable binary / Prepare-Build-Testing-With-CMake (push) Failing after 9s
Prepare Build and Testing executable binary / Prepare-Build-Testing-With-Meson (push) Successful in 12s
77 lines
1.5 KiB
C
77 lines
1.5 KiB
C
#include "file.h"
|
|
|
|
#include <fcntl.h>
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <unistd.h>
|
|
|
|
char *read_file(const char *path) {
|
|
create_file_if_not_exists(path);
|
|
FILE *fp = fopen(path, "rb");
|
|
if (fp == NULL) {
|
|
perror("Error opening file");
|
|
return nullptr;
|
|
}
|
|
|
|
fseek(fp, 0, SEEK_END);
|
|
long file_size = ftell(fp);
|
|
rewind(fp);
|
|
|
|
char *buffer = (char *) malloc(file_size + 1);
|
|
if (!buffer) {
|
|
perror("Error allocating memory");
|
|
fclose(fp);
|
|
return nullptr;
|
|
}
|
|
|
|
size_t bytes_read = fread(buffer, 1, file_size, fp);
|
|
if (bytes_read != file_size) {
|
|
perror("Error reading file");
|
|
free(buffer);
|
|
fclose(fp);
|
|
return nullptr;
|
|
}
|
|
|
|
buffer[file_size] = '\0';
|
|
fclose(fp);
|
|
return buffer;
|
|
}
|
|
|
|
char *write_file(const char *path, const char *data) {
|
|
create_file_if_not_exists(path);
|
|
FILE *fp = fopen(path, "w");
|
|
if (fp == NULL) {
|
|
printf("%s\n", path);
|
|
perror("Error opening file");
|
|
return nullptr;
|
|
}
|
|
if (fprintf(fp, "%s", data) < 0) {
|
|
perror("Error write file");
|
|
return nullptr;
|
|
}
|
|
fclose(fp);
|
|
char *ret = strdup(data);
|
|
return ret;
|
|
}
|
|
|
|
int create_file_if_not_exists(const char *filename) {
|
|
if (!check_file_exists(filename)) {
|
|
return 0;
|
|
}
|
|
FILE *file = fopen(filename, "w");
|
|
if (file == nullptr) {
|
|
perror("Error creating file");
|
|
return -1;
|
|
}
|
|
fclose(file);
|
|
return 0;
|
|
}
|
|
|
|
int check_file_exists(const char *filename) {
|
|
if (access(filename, F_OK) == 0) {
|
|
return 0;
|
|
}
|
|
return -1;
|
|
}
|