moves out the file functions into their own file

This commit is contained in:
SuperNovaa41 2025-02-06 13:54:37 -05:00
parent 29f67701c0
commit f780f45c93
4 changed files with 67 additions and 55 deletions

View File

@ -1,15 +1,16 @@
TARGET=xxd
CC=gcc
OBJ = main.o hex.o
OBJ = main.o hex.o file.o
$(TARGET): $(OBJ)
mkdir -p ../build
$(CC) -Wall -g -o $(TARGET) $(OBJ) -g
mv $(TARGET) ../build/
main.o: include/hex.h
main.o: include/hex.h include/file.h
hex.o: include/hex.h
file.o: include/file.h
.PHONY: clean
clean:

49
src/file.c Normal file
View File

@ -0,0 +1,49 @@
#include <stdio.h>
#include <stdlib.h>
#include "include/file.h"
void read_file_to_buf(const char* filename, char** buf)
{
FILE* f;
int err, bufsize, newlen;
f = fopen(filename, "r");
if (f == NULL) {
perror("fopen");
exit(EXIT_FAILURE);
}
err = fseek(f, 0L, SEEK_END);
if (err != 0) {
perror("fseek");
fclose(f);
exit(EXIT_FAILURE); }
bufsize = ftell(f);
if (bufsize == -1) {
perror("ftell");
fclose(f);
exit(EXIT_FAILURE);
}
(*buf) = malloc(sizeof(char) * (bufsize + 1));
if (*buf == NULL) {
perror("malloc");
fclose(f);
exit(EXIT_FAILURE);
}
rewind(f);
newlen = fread(*buf, sizeof(char), bufsize, f);
if (ferror(f) != 0) {
perror("fread");
fclose(f);
exit(EXIT_FAILURE);
} else {
(*buf)[newlen++] = '\0'; // just to be safe
}
fclose(f);
}

14
src/include/file.h Normal file
View File

@ -0,0 +1,14 @@
#ifndef FILE_H
#define FILE_H
/**
* read_file_to_buf
*
* - const char* filename - Name of the file we're opening
* - char** buf - pointer to the buffer to hold the file in
*
* read the file into a buffer to prevent unnecessary file ops
*/
void read_file_to_buf(const char* filename, char** buf);
#endif

View File

@ -3,59 +3,7 @@
#include <string.h>
#include "include/hex.h"
/**
* read_file_to_buf
*
* - const char* filename - Name of the file we're opening
* - char** buf - pointer to the buffer to hold the file in
*
* read the file into a buffer to prevent unnecessary file ops
*/
void read_file_to_buf(const char* filename, char** buf)
{
FILE* f;
int err, bufsize, newlen;
f = fopen(filename, "r");
if (f == NULL) {
perror("fopen");
exit(EXIT_FAILURE);
}
err = fseek(f, 0L, SEEK_END);
if (err != 0) {
perror("fseek");
fclose(f);
exit(EXIT_FAILURE); }
bufsize = ftell(f);
if (bufsize == -1) {
perror("ftell");
fclose(f);
exit(EXIT_FAILURE);
}
(*buf) = malloc(sizeof(char) * (bufsize + 1));
if (*buf == NULL) {
perror("malloc");
fclose(f);
exit(EXIT_FAILURE);
}
rewind(f);
newlen = fread(*buf, sizeof(char), bufsize, f);
if (ferror(f) != 0) {
perror("fread");
fclose(f);
exit(EXIT_FAILURE);
} else {
(*buf)[newlen++] = '\0'; // just to be safe
}
fclose(f);
}
#include "include/file.h"
int get_hex_lines(int len)
{