Hi,

I want to edit a record inside a txt file. So first a search for the record inside the file and display the record to the user. But for example, if the user want to edit the name, how I can go to that position?

void editar_cliente()
{
 
 int Cli_num = 0, seleccion = 0, pointer_Pos;
 
 string Cli_nombre, Cli_apellido, Cli_dirr, dummy, file_record, Num_client_edit, file_record_num;
 double Cli_total_compras = 0.0, Cli_balance = 0.0;        
    
 ifstream readFile;
 readFile.open("Tbl_cliente.txt", ios::in); // open a file for input
 readFile.unsetf(ios::skipws);       
 
 cout << "Please enter the number of the client you want to edit: ";
 cin >> Num_client_edit;
 
 if (!readFile.fail())
 { // if began
        
        while(getline(readFile, file_record, '#'))
        { // while began
         
            cout << file_record_num;
            if (Num_client_edit == file_record)
            {
                
                getline(readFile, Cli_nombre, '#');
                getline(readFile, Cli_apellido, '#');
                getline(readFile, Cli_dirr, '#');
                readFile >> Cli_total_compras;
                readFile.close(); 
            }
            
           // else
             //   cout << "Cliente #: " << Num_client_edit << " no se ecuentra" << endl;
        } // while end
        
 } // if end
   
 else
 {
     cerr << "Error Opening File!\a" << endl;
 }

 cout << "\n1. Client Name: " << Cli_nombre << endl;
 cout << "2. Last Name     : " << Cli_apellido << endl;
 cout << "3. Address: " << Cli_dirr << endl;        
 cout << "4. Total Purchases : " << Cli_balance << endl;
 cout << "5. Balance       : " << Cli_total_compras << endl;

 cout << "\nWhich field you want to edit?: ";
 cin >> seleccion;
 getline(cin,dummy,'\n');
 
 ofstream file;
 file.open("Tbl_cliente.txt", fstream::out); 
 
 if (seleccion == 1)
    {
      cout << "Enter the new name: ";
      getline(cin,Cli_nombre,'\n');
     
    }  
        
}

The Tbl_cliente.txt looks like:

1#Juan#Martinez#PO Box 356#0#0#
2#Pedro#Perez#PO Box 32480#0#

Any input would be appreciate.

Dani AI

Generated

Short answer: don’t try to "seek" to a field inside a variable‑length text record. The reliable approach is to read each record, modify it in memory, write records to a temporary file, then atomically replace the original. That’s the safe path hinted at; it works for the #‑delimited format you’re using (as shown in your posts).

Recommended workflow

  1. Open the original file for reading and a new temp file for writing.
  2. Read one record (a full line) at a time, split it on # into fields, and identify the record to change by ID or by line index.
  3. Modify the chosen field in the vector of fields (or extend the vector if needed).
  4. Serialize the fields back into the same delimited format and write the line to the temp file.
  5. After processing all lines, close files and replace the original with the temp file (use std::filesystem::rename or a safe platform-specific replace). Keep a .bak if you need rollback.

A short, safe C++ example (C++17) illustrating the core loop:

std::ifstream in("Tbl_cliente.txt");
std::ofstream out("Tbl_cliente.txt.tmp");
std::string line;
while (std::getline(in, line)) {
    bool trailing = !line.empty() && line.back() == '#';
    std::vector<std::string> f;
    std::stringstream ss(line);
    std::string tok;
    while (std::getline(ss, tok, '#')) f.push_back(tok);
    if (!f.empty() && f[0] == targetId) {
        if (fieldIndex < (int)f.size()) f[fieldIndex] = newValue;
        else while ((int)f.size() <= fieldIndex) f.push_back(""), f[fieldIndex] = newValue;
    }
    for (size_t i = 0; i < f.size(); ++i) { if (i) out << '#'; out << f[i]; }
    if (trailing) out << '#';
    out << '\n';
}
in.close(); out.close();
std::filesystem::rename("Tbl_cliente.txt.tmp", "Tbl_cliente.txt");

Notes and cautions

  • If you absolutely need in‑place editing, use fixed‑length records and compute byte offsets; otherwise it’s fragile.
  • Check file open errors, use backups for safety, and consider file locking if concurrent access is possible.
  • Watch for # inside fields (escape or choose a safer format like CSV/JSON if needed).

Recommended Answers

All 2 Replies

Hi,

I want to edit a record inside a txt file. So first a search for the record inside the file and display the record to the user. But for example, if the user want to edit the name, how I can go to that position?

void editar_cliente()
{
 
 int Cli_num = 0, seleccion = 0, pointer_Pos;
 
 string Cli_nombre, Cli_apellido, Cli_dirr, dummy, file_record, Num_client_edit, file_record_num;
 double Cli_total_compras = 0.0, Cli_balance = 0.0;        
    
 ifstream readFile;
 readFile.open("Tbl_cliente.txt", ios::in); // open a file for input
 readFile.unsetf(ios::skipws);       
 
 cout << "Please enter the number of the client you want to edit: ";
 cin >> Num_client_edit;
 
 if (!readFile.fail())
 { // if began
        
        while(getline(readFile, file_record, '#'))
        { // while began
         
            cout << file_record_num;
            if (Num_client_edit == file_record)
            {
                
                getline(readFile, Cli_nombre, '#');
                getline(readFile, Cli_apellido, '#');
                getline(readFile, Cli_dirr, '#');
                readFile >> Cli_total_compras;
                readFile.close(); 
            }
            
           // else
             //   cout << "Cliente #: " << Num_client_edit << " no se ecuentra" << endl;
        } // while end
        
 } // if end
   
 else
 {
     cerr << "Error Opening File!\a" << endl;
 }

 cout << "\n1. Client Name: " << Cli_nombre << endl;
 cout << "2. Last Name     : " << Cli_apellido << endl;
 cout << "3. Address: " << Cli_dirr << endl;        
 cout << "4. Total Purchases : " << Cli_balance << endl;
 cout << "5. Balance       : " << Cli_total_compras << endl;

 cout << "\nWhich field you want to edit?: ";
 cin >> seleccion;
 getline(cin,dummy,'\n');
 
 ofstream file;
 file.open("Tbl_cliente.txt", fstream::out); 
 
 if (seleccion == 1)
    {
      cout << "Enter the new name: ";
      getline(cin,Cli_nombre,'\n');
     
    }  
        
}

The Tbl_cliente.txt looks like:

1#Juan#Martinez#PO Box 356#0#0#
2#Pedro#Perez#PO Box 32480#0#

Any input would be appreciate.

OK to be more specific, I already know the number of the that I want to update, lets say is line number 5. How I move the pointer to that line so I can proceed doing the update?

Depends what you want to do when the edit has been completed. If you want to write corrected information back to file then you need to write the whole file into your program, edit the record, then rewrite the whole file back to file. IF the edit takes up exactly the same memory as the original, then you can just write the edit to the file (it isn't quite as straightforward as it sounds, though it is doable), but that doesn't seem likely in many instances of needing to edit in your program.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.