Last active
October 14, 2024 00:04
-
-
Save waldnercharles/481b9b7b25deb70c07de35e355b9c153 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdint.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <stdint.h> | |
char *read_entire_file_to_memory_and_nul_terminate(const char *filename, size_t *file_size) | |
{ | |
FILE* file = fopen(filename, "rb"); | |
if (file == NULL) { | |
perror("Failed to open file"); | |
return NULL; | |
} | |
fseek(file, 0, SEEK_END); | |
size_t sz = ftell(file); | |
rewind(file); | |
char *buf = (char *)malloc(sz + 1); | |
if (buf == NULL) { | |
perror("Failed to allocate memory"); | |
fclose(file); | |
return NULL; | |
} | |
size_t bytes_read = fread(buf, sizeof(char), sz, file); | |
if (bytes_read != sz) { | |
perror("Failed to read file"); | |
free(buf); | |
fclose(file); | |
return NULL; | |
} | |
buf[bytes_read] = '\0'; | |
if (file_size) { *file_size = sz; } | |
return buf; | |
} | |
void normalize_line_endings(char *buffer) | |
{ | |
char *src = buffer; | |
char *dst = buffer; | |
while (*src) { | |
if (*src == '\r') { | |
if (*(src + 1) == '\n') { src++; } | |
*dst++ = '\n'; | |
} else { | |
*dst++ = *src; | |
} | |
src++; | |
} | |
*dst = '\0'; | |
} | |
void merge_lines_ending_in_backslash(char *buffer) | |
{ | |
char *src = buffer; | |
char *dst = buffer; | |
while (*src) { | |
if (*src == '\\' && (*(src + 1) == '\n')) { | |
src += 2; // Move past the \ and LF | |
} else { | |
*dst++ = *src++; | |
} | |
} | |
*dst = '\0'; | |
} | |
void remove_comments(char *buffer) | |
{ | |
char *src = buffer; | |
char *dst = buffer; | |
while (*src) { | |
// Multi-line comments | |
if (*src == '/' && *(src + 1) == '*') { | |
src += 2; // Move past "/*" | |
while (*src && !(*src == '*' && *(src + 1) == '/')) { | |
src++; | |
} | |
if (*src) { | |
src += 2; // Move past "*/" | |
} | |
*dst++ = ' '; | |
} | |
// Single-line comments | |
else if (*src == '/' && *(src + 1) == '/') { | |
src += 2; // Move past "//" | |
while (*src && *src != '\n') { | |
src++; | |
} | |
*dst++ = ' '; | |
} | |
else { | |
*dst++ = *src++; | |
} | |
} | |
*dst = '\0'; | |
} | |
int main(void) { | |
char *test = "/\\\n" | |
"*\n" | |
"*/ # /*\n" | |
"*/ defi\\\n" | |
"ne FO\\\n" | |
"O 10\\\n" | |
"20"; | |
// read_entire_file_to_memory_and_nul_terminate("test.h", NULL); | |
normalize_line_endings(test); | |
merge_lines_ending_in_backslash(test); | |
remove_comments(test); | |
printf(test); // Prints " # define FOO 1020" | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment