💾 Archived View for sdf.org › blippy › c.gmi captured on 2023-01-29 at 03:44:25. Gemini links have been rewritten to link to archived content

View Raw

More Information

➡️ Next capture (2023-01-29)

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

C/C++ programming language

Created 2022-12-15 Updated 2023-01-15

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

EXITS

Module example