Added helper functions for file manipulation

master
Aadhavan Srinivasan 2 years ago
parent e5e3e8db72
commit 13858dc352

@ -0,0 +1,51 @@
#include <stdlib.h>
#include <stdio.h>
#include "file_helpers.h"
char* file_to_string(char* filename) {
FILE* fp = fopen(filename,"r");
fseek(fp,0,SEEK_END);
long file_size = ftell(fp);
rewind(fp);
char* buffer = calloc(sizeof(char),file_size+1);
fread(buffer,1,file_size,fp);
fclose(fp);
return buffer;
}
/* Finds the number of lines in a file (Which MUST end in a new-line, if the last
line is to be counted) */
int num_of_lines(char* filename) {
int num_lines = 0;
FILE* fp = fopen(filename,"r");
if (fp == NULL) {
return -1;
}
for (int c = getc(fp); c != EOF; c = getc(fp)) {
if (c == '\n') {
num_lines++;
}
}
fclose(fp);
return num_lines;
}
Loading…
Cancel
Save