Hi. I was wondering if anybody could help me with a small problem.

I would like to read a specific line from a txtfile and either output/delete it.
Basically, I'm doing a program where a user inputs/view records and i'm stuck at searching it.
My txtfile input from user has a format like this:
ID:
Name:
Contact:
etc...
and it repeats.

So i would like to search by ID and output the id,name,contact...etc.
Anyone could give me a hand here?:sad:

Dani AI

Generated

Brief summary and practical approach

The file format shown by is best treated as repeating key:value records (ID:, Name:, Contact:, …). Searching by a line number (as in ) is brittle — any inserted/removed line breaks will break the lookup. A more robust, low-dependency approach is to stream the file, parse each record into a small map or struct, and compare the parsed ID field. That follows the spirit of ’s matching idea and ’s struct suggestion but keeps memory use low.

A concise C++ example that finds and prints the first matching record (parses key:value lines, handles records separated by blank lines or by encountering the next ID) follows:

#include <fstream>
#include <string>
#include <map>
#include <iostream>

bool findRecordByID(const std::string& path, const std::string& id) {
    std::ifstream in(path);
    if (!in) return false;
    auto trim = [](std::string s){
        size_t a = s.find_first_not_of(" \t\r\n");
        if (a==std::string::npos) return std::string();
        size_t b = s.find_last_not_of(" \t\r\n");
        return s.substr(a, b-a+1);
    };
    std::map<std::string,std::string> rec;
    std::string line;
    while (std::getline(in,line)) {
        if (line.empty()) {
            if (!rec.empty()) {
                if (rec.count("ID") && trim(rec["ID"]) == id) {
                    for (auto &kv : rec) std::cout << kv.first << ": " << kv.second << "\n";
                    return true;
                }
                rec.clear();
            }
            continue;
        }
        auto p = line.find(':');
        if (p == std::string::npos) continue;
        rec[ trim(line.substr(0,p)) ] = trim(line.substr(p+1));
    }
    if (!rec.empty() && rec.count("ID") && trim(rec["ID"]) == id) {
        for (auto &kv : rec) std::cout << kv.first << ": " << kv.second << "\n";
        return true;
    }
    return false;
}

Deleting a record
Do an on-the-fly copy to a temporary file: parse each record, write it to the temp file unless its ID matches the one to remove, then atomically replace the original with the temp file. That streams data (no full-file memory use) and matches ’s safer suggestion.

When to consider alternatives
For very large datasets or frequent random lookups, maintain an index of ID→file-offset (build once, update on changes), use fixed-length records and fseek, or adopt a lightweight DB (SQLite) to avoid fragile text parsing. Edge cases: duplicate IDs, inconsistent whitespace/line endings, malformed lines — implement trimming and decide whether matching should be case-sensitive.

Recommended Answers

All 6 Replies

Anyone will be glad to give you hand if you show your efforts here.
If you don't really know how to work with files then I would suggest you to read you book first or go through basic tutorial like
File I/O in C
File I/O in C++

Uhm I think you misunderstand me. I've done it; I'm just stuck on searching data from a file. I was hoping someone could give an example on it. I do not want it to be from my coding just an irrelevant example.
And I did read the two links you gave..

Well if you've already created functions to read a whole record and write a whole record, then perhaps something like

int matchID ( record *rec, char *ID ) {
  return strcmp( rec->ID, ID );
}

Based on the result, you can decide whether (or not) to output the record to the screen, another file or whatever.

Member Avatar for Member #46692

Hi. I was wondering if anybody could help me with a small problem.

I would like to read a specific line from a txtfile and either output/delete it.
Basically, I'm doing a program where a user inputs/view records and i'm stuck at searching it.
My txtfile input from user has a format like this:
ID:
Name:
Contact:
etc...
and it repeats.

So i would like to search by ID and output the id,name,contact...etc.
Anyone could give me a hand here?:sad:

You neglected to mention what variant of the c language you intend to use, c or c++?

In any case here is how I would do it . Create a class or structure and separate it into three attributes. ID, name and contact.

Read the file three lines at a time, feeding each line into the class/structure. I.e.

line one => ID: 398439
line two => name: iamthwee
line three=>contact: 00349303

You can use the ':' (colon) as a delimiter to split each line into two parts. The right-hand part is the most important bit and you will feed this into the class/structure variables.

Then, once you have an array of class/structure variables, traverse through the array, matching either the ID/name/contact details.

Use the 'string.find' API for c++ or make your own find function using 'strcmp' if you intend to use 'c'.

In regards to the how do 'I delete a line from the file problem',you should know that deleting doesn't actually exist.

Rather, you give the illusion of deletion by:-

1. copying the contents of the original file into memory,
2. change the a variable of that file whilst in memory,
3. erase the original file,
4. then write a new file with the ammendments and then rename the new file with the name of the original one.

In regards to the how do 'I delete a line from the file problem',you should know that deleting doesn't actually exist.

Rather, you give the illusion of deletion by:-

1. copying the contents of the original file into memory,
2. change the a variable of that file whilst in memory,
3. erase the original file,
4. then write a new file with the ammendments and then rename the new file with the name of the original one.

Wont this present problems if the file is really large like those real time log files or data files. It would be really better if you read a chunk or a logical structure of data from the original file and keep on writing it to a new file and skip those records which you want to as such delete as you say. After this operation if finished the original file can be overwritten with the new one or deleted.

just my point of view, bye.

If you want to read a particular line perhaps this could help. Suppose you want to read line no.131 then use the following code:

ifstream fin("file.dat");
int lineno = 131;
int count = 0;
string str;
while(count < 130 && getline(fin, str))
    count++;
getline(fin, str);
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.