C/C++ programming language
Created 2022-12-15 Updated 2023-05-06
TABLE OF OTHER CONTENTS
COMPUTED GOTOS
static void* where = &&some_label;
goto *where;
some_label:
do_something();
FUNCTION POINTER TYPEDEF
typedef void (*fptr)(void); // takes no args, returns void
void hello(void)
{
puts("hello world");
}
int main()
{
fptr fn = &hello;
fn();
}
GNU COMPILER
Weak pointers
void __attribute__((weak)) my_function(char ch)
{
...
}
SLURP FILE
#include#include char *source = NULL; long source_len; char* slurp(char* filename, long *len) { FILE *fp = fopen(filename, "r"); if(fp == NULL) return 0; char* source = 0; *len = -1; // find its length if (fseek(fp, 0L, SEEK_END) != 0) goto finis; *len = ftell(fp); if (*len == -1) goto finis; source = malloc(sizeof(char) * (*len + 1)); /* Go back to the start of the file. */ if (fseek(fp, 0L, SEEK_SET) != 0) { /* Error */ } /* Read the entire file into memory. */ size_t newLen = fread(source, sizeof(char), *len, fp); if (newLen == 0) { fputs("Error reading file", stderr); } else { source[newLen] = '\0'; /* Just to be safe. */ } finis: fclose(fp); return source; } void main() { source = slurp("prog1.s", &source_len); for(int i = 0; i < source_len; i++) putchar(source[i]); free(source); }
C++
#include#include std::string slurp(const char *filename) { std::ifstream in; in.open(filename, std::ifstream::in | std::ifstream::binary); std::stringstream sstr; sstr << in.rdbuf(); in.close(); return sstr.str(); }
SPIT FILE
C++
(Works with binary text, too)
#includebool spit (const string& path, const string &text) { fstream file; file.open(path, ios_base::out); if(!file.is_open()) return false; file< EXITS