obernardovieira

Substituir texto de ficheiro! (com fstream)

Jul 6th, 2013
181
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.16 KB | None | 0 0
  1. /*
  2. Crie um ficheiro (formato .txt) dentro do disco C: com
  3. o nome texto "texto" e dentro dele escreva o seguinte texto
  4.  
  5. "Ola, isto é um teste.
  6. Mais um!
  7. Finalizou!"
  8.  
  9. */
  10. #include <iostream>
  11. #include <fstream>
  12. #include <string>
  13.  
  14. using namespace std;
  15.  
  16. int main () {
  17.     string linha;
  18.     string textoc;
  19.  
  20.     fstream aficheiro ("C:\\texto.txt");
  21.     if (aficheiro.is_open())
  22.     {
  23.         while (! aficheiro.eof() )
  24.         {
  25.             getline(aficheiro, linha);
  26.             textoc.insert(textoc.length(), linha);
  27.             textoc.insert(textoc.length(), "\n");//adiciona a quebra de linha (nao detetada na leitura!)
  28.         }
  29.         aficheiro.close();
  30.     }
  31.     else {
  32.         cout << "Impossivel abrir o ficheiro!" << endl;
  33.     }
  34.  
  35.  
  36.     ofstream eficheiro;
  37.     eficheiro.open ("C:\\texto.txt");
  38.     if(eficheiro.is_open()) {
  39.         size_t encontra = textoc.find("Mais um!");
  40.         if(encontra != string::npos) {
  41.             textoc.replace(textoc.begin()+encontra, textoc.begin()+encontra+8, "Menos um!");
  42.             cout << "Sucesso!" << endl;
  43.         }
  44.         else {
  45.             cout << "Erro na pesquisa!"<<endl;
  46.         }
  47.         eficheiro << textoc << endl;
  48.         eficheiro.close();
  49.     }
  50.     else {
  51.         cout << "Impossivel abrir o ficheiro!" << endl;
  52.     }
  53.     system("pause");
  54.     return 0;
  55. }
Add Comment
Please, Sign In to add comment