diff options
| author | Tyge Løvset <[email protected]> | 2023-03-01 14:54:36 +0100 |
|---|---|---|
| committer | Tyge Løvset <[email protected]> | 2023-03-01 14:54:36 +0100 |
| commit | a203314647b5c37c7e40230551457f006ff36cd5 (patch) | |
| tree | 3d8b9b29595577bee0926434820d602a29487ea3 /misc/examples/coread.c | |
| parent | 78a7e85535fd02e643bf98103223d4218e80133f (diff) | |
| download | STC-modified-a203314647b5c37c7e40230551457f006ff36cd5.tar.gz STC-modified-a203314647b5c37c7e40230551457f006ff36cd5.zip | |
Reverted example moves.
Diffstat (limited to 'misc/examples/coread.c')
| -rw-r--r-- | misc/examples/coread.c | 36 |
1 files changed, 36 insertions, 0 deletions
diff --git a/misc/examples/coread.c b/misc/examples/coread.c new file mode 100644 index 00000000..c5f85e08 --- /dev/null +++ b/misc/examples/coread.c @@ -0,0 +1,36 @@ +#include <stc/cstr.h> +#include <stc/algo/coroutine.h> +#include <errno.h> + +// Read file line by line using coroutines: + +struct file_nextline { + const char* filename; + int cco_state; + FILE* fp; + cstr line; +}; + +bool file_nextline(struct file_nextline* U) +{ + cco_begin(U) + U->fp = fopen(U->filename, "r"); + U->line = cstr_init(); + + while (cstr_getline(&U->line, U->fp)) + cco_yield(true); + + cco_final: // required label. + printf("finish\n"); + cstr_drop(&U->line); + fclose(U->fp); + cco_end(false); +} + +int main(void) { + struct file_nextline z = {__FILE__}; + int n = 0; + while (file_nextline(&z)) { + printf("%3d %s\n", ++n, cstr_str(&z.line)); + } +} |
