Insert and Concatenate Text in a C ++ file

0

I want to insert multiple lines in a .txt file and read the entire .txt file to validate the inserts, the problem is that it always shows me only one line. I insert text into a function and I send it to call many times.

This is my function to insert text:

int escribirEnArchivo(string texto)
{
    char in[20 + 1] = {0};
    char out[80 + 1] = {0};
    char str[400] = {0};
    FILE *file;

    memset(in, 0, sizeof(in));
    memset(out, 0, sizeof(out));
    memset(str, 0, sizeof(str));

    strcpy(in, texto.c_str());

    file = fopen("Prueba.txt", "a");
    fputs((char*)in, file);
    fclose(file);

    file = fopen("Prueba.txt", "r");
    fgets(out, 80, (FILE*)file);
    fclose(file);

    cout<<out<<endl;

    return 1;
}

Always print only: 1|Hola Mundo!|25.00|true

This function calls the insert several times:

int foo()
{
    escribirEnArchivo("1|Hola Mundo!|20.00|true");
    escribirEnArchivo("2|Adios Mundo!|50.00|false");
    escribirEnArchivo("3|Hola Mundo!|75.00|true");
}
    
asked by Noe Cano 05.10.2018 в 00:20
source

1 answer

2

In your code you use many classic C functions oriented to arrays ending in '\ 0', such as strcpy() , fputs() and fgets() . However, in C ++ you can use the "streams" type objects that encapsulate the need to use write, read, calculate and maintain the size of your buffers as in in[20+1]; out[40+1] , I suspect that by keeping a fixed size of 21 and 41 bytes only you reach to read the first line.

When rewriting your code using stream we see that it is much simpler:

#include <iostream>
#include <fstream>

using namespace std;

int escribirEnArchivo(string texto)
{
    ofstream out_file;  // Output File Stream para escribir (writing)
    ifstream in_file;   // Input File Stream  para leer (reading)

    // Escribir el archivo
    out_file.open("Prueba.txt", ios::app); // ios::app es lo paralello a "a" que significa append agregar al final del archivo
    out_file << texto << endl; // agregamos al buffer del stream
    out_file.close();  // flush el buffer y cerramos. flush el buffer basicamente hace write en el archivo.

    // Leer el archivo
    in_file.open("Prueba.txt");
    cout << "[Prueba.txt]  >>>" << endl;
    cout << in_file.rdbuf(); //endl funciona como activador de flush()
    // in_file.close() es llamado automaticamente en el destructor de in_file
    return 1;
}

int main() {
    escribirEnArchivo("1|Hola Mundo!|20.00|true");
    escribirEnArchivo("2|Adios Mundo!|50.00|false");
    escribirEnArchivo("3|Hola Mundo!|75.00|true");
}
    
answered by 07.10.2018 / 11:16
source