Read file .txt and enter data read in variables


I had a question about how to read a text file in which the data come one in each line and enter them in the variables that I want.

Let me explain:

#include <stdio.h>

int main()

char fichero[100], nombre[100], apellido[100];
int edad;

FILE *f;

printf("\n\nIntroduce el fichero desde donde quieras importar los datos: ");
gets(fichero); //Introduzco Manualmente el nombre del fichero

f = fopen(fichero, "r"); //Abro el fichero en modo lectura 
                         **//****ES UN ARCHIVO .TXT******
if(f == NULL)    //Compruebo que se ha abierto correctamente
  printf("Error.No se ha podido abrir el fichero");
fgets(nombre, 100, f);  //Utilizo la funcion fgets para coger cadena de
fscanf(f, "%d", &edad);  //caracteres y fscanf para tomar numeros y los 
fgets(apellido, 100, f); //guardo en las variables anteriormente creadas

printf("\n\nDATOS");   //Muestro esas variables por pantalla
printf("\n\nNombre: %s",nombre);
printf("\nEdad: %i",edad);
printf("\nApellido: %s",apellido);
printf("\n\n\nPulse <intro> para finalizar...");

return 0;


As you can see, the only thing I'm trying to do is open the file and copy the data, but I'm not able to save it. The content of the .txt file from which you are taking the data is as follows:

Luis Miguel
Perez Hernandez

Any idea how I can do?

asked by Josemanuu 28.04.2017 в 13:06

1 answer

fscanf(f, "%d", edad);

In order that fscanf can modify the content of edad it is necessary that either said variable is a pointer or you provide a reference to said variable. The correct thing would be:

fscanf(f, "%d", &edad);
//              ^

With that I would compile you, now well:

fflush is intended to be used only with exit buffers. Using it with input buffers is somewhat discouraged because the standard does not contemplate it, then the result may vary between compilers and machines. This means that the following line is left:


If you really need to clean the input buffer you will have to resort to other artifices as long as they conform to the standard.

Another detail is that if fgets encounters a line break, it includes it in the reading string and I do not think that is what you intend. The result is that the console will show you something like this:

Luis Miguel
                 <-- Salto de linea

Here you can see another error. Where is the last name? The problem here is that scanf does not discard the line break, so the last name reading just reading the line break.

To correct these reading problems you can use something such that:

fgets(nombre, 100, f);
fscanf(f, "%d\n", &edad);      // lees la edad y descartas el salto de linea
fgets(apellido, 100, f);

nombre[strlen(nombre)-1] = 0;     // Elimina el salto de linea
apellido[strlen(apellido)-1] = 0; // Elimina el salto de linea

Note your first version did not pass edad as a reference to the function fscanf

answered by 28.04.2017 / 13:28