Read a text file and separate content into variables

0

I'm having a question on how to split information from a text file into variables in C. Example, I have a txt file with the following data:

3 2
A
D
E
AD
DE

I would like to read this file, and separate each information into a variable, for example, the number 3 in a variable, the 2 in another, A in another and so on, the letters together can be in a variable only.

So far what I got in terms of code was this:

void ler_arquivo(){
    int vertices;
    int arestas;
    FILE *arq = fopen("init.txt","r");
    if(arq != NULL){
        printf("\tSucesso!\n");
        char linha[3];
        while(!feof(arq)){
            fgets(linha,3,arq);
            printf("%s",linha);
        }
    }
}

For now I'm just printing the vector, because I do not know how to do the division into variables.

    
asked by anonymous 11.12.2018 / 13:47

1 answer

1

Incomplete example (not saving vertices and edges). Shows how to use the fscanf function to read fields from a text file.

#include <stdio.h>
#include <stdlib.h> // para exit

int main()
{
  int vertices;
  int arestas;

  int nCposLidos;  // para fscanf
  char buffer[10]; // para fscanf

  int i; // para for


  FILE *arq = fopen("init.txt","r");
  if (arq == NULL)
  {
    printf("* erro na abertura do arquivo\n");
    exit(1);
  }

  // lendo vertices
  nCposLidos = fscanf(arq, "%d", &vertices);
  if (nCposLidos != 1)
  {
    printf("* erro %d na leitura do numero de vertices\n", nCposLidos);
    exit(1);
  }

  printf("* numero de vertices: %d\n", vertices);

  // lendo arestas
  nCposLidos = fscanf(arq, "%d", &arestas);
  if (nCposLidos != 1)
  {
    printf("* erro %d na leitura do numero de arestas\n", nCposLidos);
    exit(1);
  }

  printf("* numero de arestas: %d\n", arestas);

  // lendo nomes dos vertices, 1 por linha

  for (i = 0; i < vertices; i++)
  {
    nCposLidos = fscanf(arq, " %s", buffer);
    if (nCposLidos != 1)
    {
      printf("* erro %d na leitura de um vertice\n", nCposLidos);
      exit(1);
    }
    printf("* vertice lido: %s\n", buffer);
  }

  // lendo nomes das arestas, 1 por linha

  for (i = 0; i < arestas; i++)
  {
    nCposLidos = fscanf(arq, " %s", buffer);
    if (nCposLidos != 1)
    {
      printf("* erro %d na leitura de uma aresta\n", nCposLidos);
      exit(1);
    }
    printf("* aresta lida: %s\n", buffer);
  }

}
    
11.12.2018 / 18:16