Read a text file and separate content into variables

Asked

Viewed 407 times

0

I have a question about how to divide 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 one variable, the 2 in another, the A in another and so on, the letters together can be in one variable only.

So far what I’ve achieved in terms of code is 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 don’t know how to do the division into variables.

1 answer

1


Incomplete example (not holding the 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);
  }

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.