Hello, I have this code where it reads a string from a file that contains names in the following way
Robert Fair
Amanda Insley
Daniel Berryhill
This code compiles sometimes and others do not, even when compiling and executing it, in the file garbage is kept in addition to the word, for example
‚Jê2+b"¢?Robert Fair
B0Ê4Amanda Insley
Daniel Berryhill
êr&rGarry Puckett
Code:
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define fila 50000
#define columna 50
int EXTRAE_DATOS(char *variable, FILE *file);
int NUMEROS_AL();
int main()
{
int n,a,i=0;
char **nombre;
FILE *alias;
alias = fopen("nombres_aleatorios.txt","r");
if (alias == NULL)
{
printf("\nError: El archivo 'nombres_aleatorios.txt' no se ha encontrado.\n");
}
FILE *escribo;
escribo = fopen("nombres_generados.txt","w");
if (escribo == NULL)
{
printf("\nError: El archivo 'nombres_generados.txt' no se ha encontrado.\n");
}
nombre=(char**)malloc(fila*sizeof(char*));
for(i=0;i<fila;i++)
{
nombre[i]=(char*)malloc(columna*sizeof(char));
if(nombre[i]==NULL)
{
printf("No se ha podido reservar memoria");
exit(1);
}
}
srand(time(NULL)); //Semilla para generar números aleatorios
i=0;
fseek(alias,0,SEEK_SET);
while(!feof(alias))
{
fgets(*(nombre+i),200,alias);
i++;
}
for(n=0;n<fila;n++)
{
a=NUMEROS_AL();
fprintf(escribo,"%s",nombre[a]);
}
fclose(escribo);
fclose(alias);
free(nombre);
}
int NUMEROS_AL()
{
int num;
//numero = rand () % (N-M+1) + M; // Este está entre M (valor minimo) y N (valor maximo)
num = rand() % fila-1; //Numeros aleatorios entre 0 y 30 -> quedará entre 1 y 31
return num;
}