Last active
July 2, 2021 09:09
-
-
Save chrplr/6da7ac6d13c5076e27e3bf217093f63c to your computer and use it in GitHub Desktop.
tokenize text in C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdlib.h> | |
#include <stdio.h> | |
#include <string.h> | |
const char* DELIMITERS = "!\"#$%&'()*+,-./:;<=>?@[]^_`{|}~\\\t\n\r "; | |
int main(int argc, char* argv[]) | |
{ | |
FILE* fd; | |
char* line = NULL; | |
size_t len = 0; | |
ssize_t nread; | |
fd = (argc > 1)? fopen(argv[1],"r") : stdin; | |
if (!fd) | |
{ | |
fprintf(stderr, "Error opening file '%s'\n", argv[1]); | |
return EXIT_FAILURE; | |
} | |
while ((nread = getline(&line, &len, fd)) != -1) { | |
char* token = strtok(line, DELIMITERS); | |
while (token != NULL) { | |
puts(token); | |
token = strtok(NULL, DELIMITERS); | |
} | |
} | |
free(line); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment