💾 Archived View for sdf.org › blippy › c.gmi captured on 2024-03-21 at 15:46:03. Gemini links have been rewritten to link to archived content

View Raw

More Information

⬅️ Previous capture (2023-07-10)

🚧 View Differences

-=-=-=-=-=-=-

C/C++ programming language

Created 2022-12-15 Updated 2023-04-27

TABLE OF OTHER CONTENTS

C/C++ alternatives

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)
{
	...
}

SETJMP

#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

SLURP FILE

#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);
}

C++

#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();
}

Gist

SPIT FILE

C++

(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;
}

EXITS

Module example

STC: Smart Template Containers for C