File opperations to parse OBJ files into Matrixs.

This commit is contained in:
Afonso Clerigo Mendes de Sousa 2025-06-13 13:23:20 +01:00
parent 4703fa73c1
commit c59c838696
4 changed files with 126 additions and 4 deletions

View File

@ -1 +1,95 @@
#include "io_file_op.hpp"
#include <string.h>
FILE *w_open_file(const char *filepath)
{
if (filepath == nullptr)
{
return nullptr;
}
FILE *file = fopen(filepath, "rwb");
return file;
}
file_content w_read_file(FILE *file)
{
file_content __result = init_file_content();
if (file == nullptr)
{
fprintf(stderr, "Error: Invalid file in w_read_file\n");
return __result;
}
fseek(file, 0, SEEK_END);
long file_size = ftell(file);
if (file_size < 0)
{
fprintf(stderr, "Error: Could not determine file size.\n");
return init_file_content();
}
rewind(file);
size_t size = (size_t)file_size;
char *buffer = (char *)malloc(sizeof(char) * (size + 1));
if (buffer == NULL)
{
fprintf(stderr, "Error: Cant Allocate buffer to read.\n");
return init_file_content();
}
size_t result = fread(buffer, 1, size, file);
if (result != size)
{
fprintf(stderr, "Error: Reading error in w_read_file.\n");
free(buffer);
return init_file_content();
}
buffer[size] = '\0';
size_t line_start = 0;
char **lines = NULL;
for (size_t i = 0; i <= size; i++)
{
if (buffer[i] == '\n' || buffer[i] == '\0')
{
size_t line_length = i - line_start;
char *line = (char *)malloc(line_length + 1);
if (line == NULL)
{
for (int j = 0; j < __result.num_lines; j++)
free(lines[j]);
free(lines);
free(buffer);
fprintf(stderr, "Error: Cant Allocate line buffer.\n");
return init_file_content();
}
memcpy(line, &buffer[line_start], line_length);
line[line_length] = '\0';
char **new_lines = (char **)realloc(lines, ((size_t)(__result.num_lines + 1)) * sizeof(char *));
if (new_lines == NULL)
{
for (int j = 0; j < __result.num_lines; j++)
free(lines[j]);
free(line);
free(lines);
free(buffer);
fprintf(stderr, "Error: Cant realloc lines array.\n");
return init_file_content();
}
lines = new_lines;
lines[__result.num_lines++] = line;
line_start = i + 1;
}
}
return __result;
}
file_content init_file_content()
{
file_content r;
r.lines = NULL;
r.num_lines = 0;
return r;
}

View File

@ -1,4 +1,19 @@
#ifndef IO_FILE_OP_HPP
#define IO_FILE_OP_HPP
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
typedef struct
{
char **lines;
int num_lines;
} file_content;
FILE *w_open_file(const char *filepath);
file_content w_read_file(FILE *file);
file_content init_file_content();
#endif // !IO_FILE_OP_HPP

View File

@ -2,9 +2,22 @@
// Include the vector utilities header file
#include "vector/vec_utils.hpp"
#include "io/io_file_op.hpp"
int main()
{
file_content file_info = w_read_file(w_open_file("./CUBE.obj"));
for (size_t i = 0; i < (u_int32_t)file_info.num_lines; i++)
{
printf("Line %04zu: \t", i);
for (size_t j = 0; file_info.lines[i][j] != '\0'; j++)
{
printf("%c", file_info.lines[i][j]);
}
printf("\n");
}
free(file_info.lines);
return 0;
}