How to modify a .txt file from c ++?

6

I want to modify a file .txt from a program developed in c++ , I already have a developed code that creates the file and also reads it, but it does not modify it and I can not find how to do it.

My code is as follows:

#include <iostream>
#include <stdlib.h>
#include <fstream>

using namespace std;

void presentaMenuGeneral() {
  string contenido;
  int opcion;
do {
system("cls");
    cout << "[:]Menu principal\n" << endl;
    cout << "[1]Crear archivo de texto" << endl;
    cout << "[2]Abrir archivo de texto" << endl;
    cout << "[3]Modificar archivo de texto" << endl;
    cout << "[0]Salir del programa\n" << endl;
    cout << "Ingresa la opcion: ";
    cin >> opcion;
    switch (opcion) {
    case 0:
        break;
case 1:{
  cout << "Ingresa el contenido del archivo: ";
  cin.ignore();
  getline(cin, contenido);
  ofstream fs("nombre.txt");
  fs << contenido << endl;
  fs.close();
  cout << "El archivo ha sido creado correctamente" << endl;
  system("pause");
  break;
}
case 2:{
  ifstream fs("nombre.txt", ios::in);
  char linea[128];
  long contador = 0L;
  if(fs.fail())
  cerr << "El fichero no existe" << endl;
  else
  while(!fs.eof())
  {
      fs.getline(linea, sizeof(linea));
      cout << linea << endl;
      if((++contador % 24)==0)
      {
          cout << "continuar...";
          cin.get();
      }
  }
  fs.close();
  system("pause");
  break;
}
case 3:
        break;
default:
        cout << "\nEl numero de opcion escrito no es valido\n" << endl;
        system("pause");
    }
  } while (opcion != 0);
}

int main(){
 presentaMenuGeneral();
 return 0;
}
    
asked by Eduardo Javier Maldonado 20.08.2016 в 23:00
source

1 answer

3

There are 2 ways to modify a file:

  • Load all the contents in memory, modify what you want, and then write to the file.
  • Create a temporary file, write in that file, and finally replace the original with the temporary one.
  • Let's look at the second option (with a temporary file), which has fewer chances of failing.

    case 3:{
      string buscar;      // texto a buscar
      string reemplazar;  // reemplazar por
    
      //ingresa textos
      cout << "Ingresa el texto a buscar: ";
      cin.ignore();
      getline(cin, buscar);
      cout << "Ingresa el texto para reemplazarlo: ";
      cin.ignore();
      getline(cin, reemplazar);
    
    
      ifstream fs("nombre.txt"); //leer de este archivo
      ofstream fstemp("nombretemp.txt"); //escribir en este archivo
      if(!fs || !fstemp) //no se pudo abrir alguno de los 2
      {
        cout << "Error al abrir el archivo!" << endl;
        break;
      }
    
      //modificar linea a linea
      while(fs >> contenido)
      {
        if(contenido == buscar){  //se encontro
          contenido = reemplazar; //reemplazar
        }
        fstemp << contenido << endl;
      }
    
      //reemplazar un archivo por otro
      fs.close();
      fstemp.close();
      remove("nombre.txt");                    // borrar el original
      rename("nombretemp.txt", "nombre.txt");  // renombrar el temporal
    
      //siguiendo la logica que usaste en el resto
      cout << "El archivo ha sido modificado correctamente" << endl;
      system("pause");
      break;
    }
    
        
    answered by 21.08.2016 / 08:58
    source