Hola, amigos. Estoy desarrollando un programa que rellena las casillas de un array con una X según la posicion y las ordenes que se indiquen desde un fichero de texto que actúa como script.
En cuanto al programa, mi único problema está en la parte en donde interpreta los scripts.
Voy dividiendo linea por linea usando strtok(...), y hasta ahí todo bien. Copio el contenido del puntero que devuelve strtok hacia un buffer de 16 caracteres para no tener que preocuparme por cosas raras con punteros.
El problema viene cuando intento usar strcmp(...) para ver si la linea actual coincide con la instruccion "fill" o "inc_x". Cuando lo hace, el programa crashea.
¿Podría alguien ayudarme a solucionar mi problema, o darme una mejor idea de como hacerlo? Gracias de antemano#include <stdio.h>
#include <stdlib.h>
#define NROWS 5//32
#define NCOLUMNS 5//32
int parse_script(char filename[]){
unsigned int x = 0;
unsigned int y = 0;
char array[NROWS][NCOLUMNS];
unsigned int file_size;
unsigned int i = 0;
FILE *script_file;
char *script_content;
char *current_line;
char current_instruction[16];
for(x = 0; x < NCOLUMNS; x++){
for(y = 0; y < NROWS; y++){
array[x][y] = 'O';
}
}
///First step, read all file content before preprocess it.
script_file = fopen(filename, "r");
///If all is good, get the size of file
fseek(script_file, 0, SEEK_END);
file_size = (unsigned long ) ftell(script_file);
rewind(script_file);
///Resize the array to the size of file
script_content = (char *) calloc (1, (size_t) file_size);
///Read the data from the file and put it in the array
fread((char *)script_content, file_size, 1, script_file); ///Last step: Free resources
///Second step: Execute instruction by instruction
///The program must divide the content in lines using \n
x = 0;
y = 0;
char delimiters[] = "\r\n";
current_line = strtok((char *) script_content, delimiters);//argumentos: frase, caracter delimitador
while(current_line != NULL)
{
strncpy(current_instruction, current_line, 16);
printf("%s \n", current_line);
///Here, the program must analyze the instruction and take an action
if(strcmp("fill", current_instruction) == 0){
array[x][y] = 'X';
}
if(strcmp("inc_x", current_instruction) == 0){
x++;
}
current_line = strtok(NULL, delimiters);
}
///Third step: Show array.
printf("\nThe content of the array is: \n");
for(x = 0; x < NCOLUMNS; x++){
for(y = 0; y < NROWS; y++){
printf("%c", array[x][y]);
printf(" ");
}
printf("\n");
}
printf("End of array. Thanks for use my program\n");
free(script_content);
fclose(script_file);
}
int main(int argc, char *argv[])
{
if(argc < 2)
return -1;
if(strcmp(argv[1], "-w") == 0){
parse_script(argv[2]);
return 0;
}
printf("Invalid command!!\n");
return 0;
}
Fichero de prueba usado (escribir su ruta en la linea de comandos como parametro despues del nombre del ejecutable):
fill
inc_x