💾 Archived View for blinkyshark.chickenkiller.com › c.gmi captured on 2023-06-16 at 16:01:28. Gemini links have been rewritten to link to archived content
-=-=-=-=-=-=-
Created 2022-12-15 Updated 2023-04-27
void* label_ptr = &&some_label; goto *label_ptr; some_label: do_something();
typedef void (*fptr)(void); // takes no args, returns void void hello(void) { puts("hello world"); } int main() { fptr fn = &hello; fn(); }
void __attribute__((weak)) my_function(char ch) { ... }
#include<stdio.h> #include <setjmp.h> jmp_buf buf; void func() { puts("hello from func()"); longjmp(buf, 1); // jump to the point setup by setjmp puts("I am never printed"); } int main() { if(setjmp(buf) == 0) { //try puts("try"); func(); } else { // catch puts("catch"); } return 0; }
Output is:
try hello from func() catch
#include <stdio.h> #include <stdlib.h> 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); }
#include <fstream> #include <sstream> 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(); }
(Works with binary text, too)
#include <fstream> bool spit (const string& path, const string &text) { fstream file; file.open(path, ios_base::out); if(!file.is_open()) return false; file<<text; file.close(); return true; }