Access, read and write c ++ files [closed]

3

I was working java and I used Scanner to access the content of text files, and also Printstream to write in new files, what would be the analogous way to perform these actions in c ++? for example, in java:

public Class(Scanner sc) {
        while (!sc.hasNextInt()){
            sc.nextLine();
        ........

public void write(PrintStream out) {
        out.println("texto....");
        ......
    
asked by jarscs 01.06.2018 в 03:12
source

1 answer

6

C ++ has the data streams (stream) to files.

So, to read a file line by line:

if (std::ifstream archivo{"archivo.txt"})
{
    std::string linea{};
    while (std::getline(archivo, linea))
    {
        // 'linea' contiene la linea leida
    }
}
else
{
    std::cout << "No se pudo abrir el archivo\n";
}

And to write:

if (std::ofstream archivo{"archivo.txt"})
{
    archivo << "Información\n"; // Escribimos en el archivo.
}
else
{
    std::cout << "No se pudo abrir el archivo\n";
}
    
answered by 01.06.2018 / 07:39
source