How to upload a text file to a Linked List in C ++?

2

How about my problem is as mentioned in the title, I have knowledge of how to make simple and double lists linked in c ++, but I have no idea how to pass information from a text file to a simple list. I have a program created in c ++ with indexes in files and my program does all this:

  • Add
  • Show
  • Search
  • Delete
  • Modify
  • Show indices

But the only option I need is Show orderly . For this I am asked to use a TDA and I have to take the data from the text file and add them to the TDA to then sort and display them. My project handles 2 text files because it is indexed, some is Datos.txt (saves all the information) and another is Index.txt (saves the indexes).

The data that is requested when adding is the following:

cout << "Codigo: ";
cin.getline(Dis.codigo,10);
cout << "Nombre: ";
cin.getline(Dis.nombre,30);
cout << "Cantante: ";
cin.getline(Dis.cantante,30);
cout << "Genero: ";
cin.getline(Dis.genero,20);
cout << "Precio: ";
fflush(stdin);
cin.getline(Dis.precio,10);
cout << "Discografia: ";
cin.getline(Dis.discografia,20);
cout << "Disco agregado correctamente" << endl;
system("pause");
ofstream a("datos.txt",ios::app);
ofstream b("indice.txt",ios::app);
a.write((char*)&Dis,sizeof(Dis));
a.seekp(0,ios::end);
Ind.pos=a.tellp()/sizeof(Dis);
strcpy(Ind.codigo,codigo);
b.write((char*)&Ind,sizeof(Ind));
b.close();
a.close();

This data is saved in the Data.txt file and the code is saved in Index.txt along with a position. I hope you understand me with the approach to my problem, which is just how to add the data that is in the .txt to a simple linked list and show it in an orderly way.

    
asked by Eduardo Javier Maldonado 17.09.2016 в 07:32
source

1 answer

5

I make an attempt to understand the situation.

Mission : Dump two text files into a disk list .

➢ Creation of a TDA or TAD (abstract data type)

The first thing is to create the structure Dis (disk), in this way.

struct Dis
{
    string codigo;
    string nombre;
    string cantante;
    string genero;
    string discografia;
    string precio;

    Dis* siguiente; //Puntero al siguiente disco (importante).
};
struct Ind
{
    int pos;
    string codigo;
};

Note: This type of structure can not come in a text file, since a string is a pointer to a string of characters, which have dynamic size. That is, all integers occupy 32 or 64 bits depending on the architecture, it is always the same number, but a string, "Pedro" , does not occupy the same as "Juan" , the first 4 and the second 5, and despite that, both are of type string, then you can not do sizeof .

➢ Manage a file

For file management, you need the standard library stdio , the main should be as follows. The stdlib is sometimes needed, so we leave it, without paying attention to what it is used for.

#include <stdio.h>
#include <stdlib.h>

int main (int argc, char** argv)
{
    //Cosas por hacer.
    return 0;
}

For this it is necessary to know how the files are handled in C , although it also works in C ++ since it is a cumulative language. So I found the following link that deals with that topic:

Programming in C - File management - WikiLibros .

  • Create a pointer of type FILE .
  • Open the file using the fopen function and assign the result of the call to our pointer.
  • Do the various operations ( reading , writing , etc).
  • Close the file using the fclose function.
  • Pseudo-code:

    Abrir archivo.
    Leerlo.
    Volcarlo en lista_enlazada //Nodo.
    Cerrarlo.
    

    ➢ Open a file

    A list of opentype parameters for the fopen function are:

      

    "r" : Reading, the file must exist.

         

    "w" : Writing, it is created if it does not exist or is overwritten if it exists.

         

    "a" : Writing at the end of the content, if it does not exist it is created.

         

    "r+" : Reading and writing, the file must exist.

         

    "w+" : Read and write, it is created if it does not exist or is overwritten if it exists.

         

    "r+b" or "rb+" : Binary mode for update (read and write).

         

    "rb" : Binary mode for reading.

    In our case we are going to use Non-Binary Reading , that is, "r" , since we are handling txt files (plain text) and not images or audio.

    Code: These are steps 1 and 2 on the same line.

    FILE* archivo = fopen("Datos.txt","r"); //Para Indice.txt es lo mismo.
    

    ➢ Read a file

      

    1) Read a character.

         

    char fgetc(FILE *archivo)

         

    2) Read from a line or the indicated size.

         

    char *fgets(char *buffer, int tamano, FILE *archivo)

         

    3) Read from blocks.

         

    size_t fread(void *puntero, size_t tamano, size_t cantidad, FILE *archivo);

         

    4) Works the same as keyboard input but from a file.

         

    int fscanf(FILE *fichero, const char *formato, argumento, ...);

    In our case we are interested in fgetc , since the structure Dis can not come in a file.

    Code: This causes you to read a character.

    while(feof(archivo) == 0)
    {
        char caracter = fgetc(archivo);
        //Hacer algo con el caracter.
    }
    

    ➢ Close a file

    Code:

    fclose(archivo);
    

    We have already seen the basic operations about file operations. Now we have to think about how to dump it into the data structure Dis .

    Since you did not show a sample text file to find out how the data of the disk might come, I'm going to assume you have the following format What's more, I think that in this way you do not need to read the index file , so I will not touch that topic.

      

    code_1 name_1 singer_1 genre_1 discography_1 price_1

         

    code_2 name_2 singer_2 genre_2 discography_2 price_2

         

    Etcetera ...

    For that you have to take into account two exceptions, any character except the spaces, (that is, ' ' , '\x20' ), or a line break, ( '\n , \r , \x0D , \x0A ). Space means the next field of the structure, the line break, the next disk.

    ➢ How to read a file with this new format?

    Code: We take back the previous code about reading the character and we add things to it.

    Dis discos = new Dis()
    string texto="";
    int i=0; //Número de campo actual.
    string campos[6]; //Array de campos de texto que luego pasarán a los discos.
    while(feof(archivo) == 0)
    {
        char caracter = fgetc(archivo);
        if( caracter!=' ' && ! esSaltoLinea(caracter) )
        {
            texto = texto+((string)(caracter)); //Agrega un caracter al final del texto
        }
        else
        {
            campos[i] = texto;
            texto = "";
            if( caracter==' ' ){i++;} //Suma 1 a la variable i.
    
            if( esSaltoLinea(caracter) )
            {
                //Volcar los textos de la variable campos al disco actual mediante un for.
                //Cambiar al disco siguiente.
    
                i=0; //Vuelve al campo inicial.
            }
        }
    }
    

    Note: I leave some things undone so you can practice quiet, they are not that difficult either.

    ➢ Ordering a structure

    In the following example I will sort the discs by code. It is necessary to clarify that the most efficient method of ordering is the one that allows the binary search, this is effective only and is slow in comparison with the other.

    void ordenarPorCodigo( Dis discos )
    {
        Dis* principal = discos;
        Dis* actual = principal;
        Dis* auxiliar;
    
        while( actual->siguiente!=NULL )
        {
            siguiente = actual->siguiente;
    
            if(  strcmp(actual->codigo,actual->siguiente->codigo) > 0 )
            {
                //Copiar los datos del actual en auxiliar.
                //Copiar los datos del siguiente en actual.
                //Copiar los datos del auxiliar en el siguiente.
    
                //Ajustar los punteros del actual y del siguiente de manera correcta.
    
                actual = principal;
            }
            actual = actual->siguiente;
        }
    }
    

    Note: Again, I leave you as a challenge those little details.

        
    answered by 17.09.2016 / 17:21
    source