c - Estudio de strtok, scanf
A vueltas con el tema de final de linea, los tokens de un string, y la entrada formateada o funciones scanf-fscanf.
/**
* tokens.c
*
* Codigo para probar:
* 0. pruebas de input formateado: scanf
* 1. lectura de un fichero de properties:
* ...
* nombre=valor
* nombre'=valor'
* ...
*
* 2. el uso de la funcion strtok
*
*/
#include <stdio.h>
#include <string.h>
int main (int argc, char *argv[]) {
int i;
char prueba[] = "vamos= a ver=si nos = entendemos=o que";
// Inicializamos con null
char test[255];
char test1[255];
char test2[255];
char* tmp = ' ';
char* token = ' ';
FILE* configuracion;
printf("Escribe algo tipo nombre=valor
");
// al loro: buscamos dos cadenas alfanumericas de 255 chars separadas por un =
if (scanf("%255[a-zA-Z0-9] = %255[a-zA-Z0-9]", &test1, &test2) < 2 ) {
printf("La kaguemusa!
");
} else {
printf("Hay algo: %s - %s
", test1, test2);
}
/********************* FICHERO PROPERTIES ******************/
if ( !(configuracion = fopen("configuracion.conf","r")) ) {
printf("Ocurrio un error al abrir fichero.
");
perror("Error al leer fichero.");
}
printf("Ok fichero abierto, vamos a sacar propiedades
");
// vamos a leer lineas de properties
while( !feof(configuracion) ) {
// esto no parece colar
// i = fscanf(configuracion,"%255[a-zA-Z0-9] = %255[a-zA-Z0-9]", &test1, &test2);
i = fscanf(configuracion,"%s",&test1);
//printf("Hay algo: %s - %s
", test1, test2);
printf("Hay algo: %s - %s
", test1, test2);
}
close(configuracion);
/********************* FIN FICHERO PROPERTIES ******************/
/********************* STRTOK ******************/
printf("
Todo OK
");
tmp = strtok(prueba,"=");
printf("Estado despues de 1 strtok: %s
",tmp);
while ( (token = strtok(NULL,"=")) != ' ') {
printf("Jar: [%s]
",token);
}
/********************* FIN STRTOK ******************/
scanf("%d",i);
return 0;
}
pello.io