C ++ write to files

4
#include <fstream>
#include <iostream>

using namespace std;

int main()
{
    ofstream f_out;
    f_out.open("teste.txt");

    if(! f_out.good())
        return -1;
    else cout << "Arquivo criado!";

    string str = "String";
    f_out << str;

    f_out.close();

    return 0;
}

This code should write to a txt file, but it does not. What should I do to make anything writable in a txt file by using the open function to open the file?

    
asked by anonymous 12.05.2015 / 21:46

1 answer

1

You may be using ofstream which is an output stream class that operates on files.

EDIT : Remember to be passing the open mode and the complete directory of the file you want to manipulate if it is not in the same folder as your program's executable.

Example : f_out.open("C:\Users\Pasta\teste.txt", std::ios::app);

See also reference C ++ Reference

std::ofstream Hypnos_FILE;
std::string TEXTO = "Escrevendo em arquivo de texto";
Hypnos_FILE.open("DATABASE\Arquivo.txt", std::ios::app);
if (Hypnos_FILE.is_open())
{
   std::cout << "Arquivo de texto aberto com sucesso!" << std::endl;

   Hypnos_FILE << TEXTO;

}
else
   std::cout << "Erro ao abrir arquivo de texto.";

Hypnos_FILE.close();

open (filename, mode);

ios :: in = Open for input operations.

ios :: out = Open for exit operations.

ios :: binary = Open in binary mode.

ios :: ate = Set the starting position at the end of the file. If this flag is not set, the starting position is the beginning of the file.

ios :: app = All output operations are performed at the end of the file, adding content to the current contents of the file.

ios :: trunc = If the file is opened for output operations and it already existed, its previous content is deleted and replaced with a new one.

    
12.05.2015 / 22:18