demo de strtok

This commit is contained in:
tTh 2023-09-01 12:37:36 +02:00
parent db14adeb86
commit 9d08631b32
3 changed files with 57 additions and 0 deletions

1
code/C/.gitignore vendored
View File

@ -1 +1,2 @@
fgets-simple fgets-simple
demo-strtok

View File

@ -2,6 +2,8 @@
# exemples pour le chapitre sur le C # exemples pour le chapitre sur le C
# new Sat Feb 11 12:06:34 CET 2023 # new Sat Feb 11 12:06:34 CET 2023
all: no-op slowprint fgets-simple
no-op: no-op.c Makefile no-op: no-op.c Makefile
gcc -Wall $< -o $@ gcc -Wall $< -o $@
@ -11,3 +13,5 @@ slowprint: slowprint.c Makefile
fgets-simple: fgets-simple.c Makefile fgets-simple: fgets-simple.c Makefile
gcc -Wall $< -o $@ gcc -Wall $< -o $@
demo-strtok: demo-strtok.c Makefile
gcc -Wall $< -o $@

52
code/C/demo-strtok.c Normal file
View File

@ -0,0 +1,52 @@
/*
* demo strtok
*/
#include <stdio.h>
#include <string.h>
#include <ctype.h>
/*---------------------------------------------------------------------*/
void dump_line(char *titre, char *ligne, int combien)
{
int foo;
unsigned char *ptr;
printf(" --- %s\n", titre);
ptr = (unsigned char *)ligne;
for (foo=0; foo<combien; foo++) {
printf("%02x ", ptr[foo]);
}
puts("");
for (foo=0; foo<combien; foo++) {
printf(" %c ", isprint(ptr[foo]) ? ptr[foo] : '?');
}
puts("");
}
/*---------------------------------------------------------------------*/
int main(int argc, char *argv[])
{
char input[] = "foo bar quux quiz";
char *cptr, *copie;
int foo;
dump_line("original", input, sizeof(input));
copie = strdup(input);
dump_line("copie", copie, sizeof(input));
puts("");
cptr = strtok(copie, " \t");
dump_line("1er strtok", copie, sizeof(input));
printf(" got [%s]\n", cptr);
puts("");
cptr = strtok(NULL, " \t");
cptr = strtok(NULL, " \t");
dump_line("2eme & 3me strtok", copie, sizeof(input));
foo = cptr - copie;
printf(" index = %d\n", foo);
printf(" and we have [%s]\n", input+foo);
return 0;
}
/*---------------------------------------------------------------------*/