feat: file2char

This commit is contained in:
dancingCycle 2023-01-20 11:44:46 +01:00
parent f0e0903cd9
commit cc9d6f3526
3 changed files with 161 additions and 0 deletions

119
file2char/main.c Normal file
View File

@ -0,0 +1,119 @@
/*to use exit*/
#include <stdlib.h>
/*to use *print**/
#include <stdio.h>
/*
* load_file reads the file identified by 'path' into a character buffer
* pointed at by 'buf'.
* On success, the size of the file is returned.
* On failure, exit(EXIT_FAILURE) is returned and.
*
* WARNING: load_file malloc()s memory to '*buf' which must be freed by
* the caller.
*/
int load_file(char const* path, char **buf){
/*declarations*/
FILE *fp;
long lSize;
/*fopen()
*filename
*mode
*return: set errno value in error case
*/
fp=fopen(path,"r");
if(fp){
fprintf(stdout,"file opened.\n");
/*set offset to file end*/
/*fseek()
*stream
*offset
*origin
*/
fseek(fp,0L,SEEK_END);
if (ferror(fp)){
printf ("Error seeking file\n");
}
/*get file size*/
lSize = ftell( fp );
fprintf(stdout,"lSize: %ld.\n",lSize);
/*set offset to file start*/
fseek(fp,0,SEEK_SET);
if (ferror(fp)){
printf ("Error seeking file\n");
}
/*allocate memory for entire content + null termination*/
*buf=(char *)malloc((lSize+1)*sizeof(char));
if(!*buf){
fclose(fp);
fputs("Error allocating memory",stderr);
exit(EXIT_FAILURE);
}
fprintf(stdout,"mem allocated.\n");
/*copy file into buffer*/
/*fread()
*ptr
*size
*count
*stream
*/
if( 1!=fread(*buf,lSize,1,fp)){
fclose(fp);
free(*buf);
fputs("Error reading entire file",stderr);
exit(EXIT_FAILURE);
}
fprintf(stdout,"file read.\n");
/*close file*/
if(EOF==fclose(fp)){
free(*buf);
exit(EXIT_FAILURE);
}
fprintf(stdout,"file closed.\n");
(*buf)[lSize] = '\0';
fprintf(stdout,"mem null terminated.\n");
/*TODO Cleanup debugging!*/
/*
for (int i = 0; i < lSize; i++) {
printf("buffer[%d] == %c\n", i, buffer[i]);
}
*/
printf("buffer = %s\n", *buf);
}else{
perror(path);
exit(EXIT_FAILURE);
}
/*done*/
return lSize;
}
int main(int argc, char** argv){
/*declaration*/
int fileSize;
char *buf;
fprintf(stdout,"main() Started...\n");
if (argc != 2) {
fprintf(stderr, "Usage: %s <file path>\n", argv[0]);
exit(EXIT_FAILURE);
}
fileSize = load_file(argv[1], &buf);
free(buf);
fprintf(stdout,"main() fileSize: %d.\n",fileSize);
fprintf(stdout,"main() Done.\n");
return 0;
}

19
file2char/makefile Normal file
View File

@ -0,0 +1,19 @@
#target: dependency_1 dependency_2 dependency_3 ...
# command
#
RM = /bin/rm -f
OBJ = main.o
EXE = main
CC = /usr/bin/gcc
CFLAGS = -Wall
#
all: $(EXE)
#
$(EXE): $(OBJ)
$(CC) $(CFLAGS) $(OBJ) -o $(EXE)
#
main.o: main.c
$(CC) -c main.c -o main.o
#
clean:
$(RM) $(OBJ) $(EXE) *~

23
file2char/readme.md Normal file
View File

@ -0,0 +1,23 @@
* build
```
make clean all
```
* cleanup
```
make clean
```
* run
```
./main <file path>
```
* run Valgrind tool `Memcheck`
```
valgrind --leak-check=yes -s ./main <file path>
```