Skip to content

Latest commit

 

History

5 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 

Repository files navigation

fstr.c - Dynamic strings for C

fstr.c - (Flexible String) provides few a simple functions for dealing with dynamically allocated string. Inspiration was taken from sds.

Warning

This is a learning project and is not inteded for the real world use.

If you like this idea then please check out sds, it's a much better implementation of this concept.

Usage

Just download fstr.h and fstr.c in to your project and #include "fstr.h" where needed.

Example:

#include "fstr.h"
#include <stdio.h>

int main() {
  fstr mystring = fstr_from("Hello");
  mystring = fstr_cat(mystring, ", ");
  mystring = fstr_cat(mystring, "World!");
  printf("%s\n", mystring);

  fstr s = fstr_new();
  s = fstr_cat(fstr_cat(s, "You can also"), " nest those functions!");
  printf("%s\n", s);

  fstr_free(mystring);
  fstr_free(s);
  return 0;
}

Outputs:

Hello, World!
You can also nest those functions!

Check out fstr.h for full list of available functions

How it works

As you can see the fstr type acts as char * but also grows dynamically. Under the hood fstr is defined as typedef char *fstr; while the actual string data is stored in this struct:

/* This struct is allocated on fstr creation (fstr_new, fstr_from, ...) */
struct fstr_header_t {
  size_t length; // Length (in bytes), acts the same as strlen()
  size_t size;   // Size of an allocation NOT including this struct and null terminator
  char string[]; // Actual string data
  //   ^
  //   +--- On fstr creation you get a pointer to here!
};

About

Dynamic strings for C

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages