I have a text file and i want to replace a word from a specific location. For example want to replace 5th word from 12th line of file. How i can do that?

Dani AI

Generated

asked how to replace the 5th word on line 12. A safe, general approach is to stream the file, write a modified copy and then atomically swap the files — this follows the idea hinted at by and keeps work minimal as suggested. The short, practical implementation below is 1-indexed (line 12 = lineNo 12, 5th word = wordIndex 5), treats a "word" as a contiguous run of non-whitespace characters, and preserves the rest of the file unchanged except for the target token.

#include <fstream>
#include <string>
#include <cstdio>
#include <cctype>

static std::string replaceNthToken(const std::string &line, int n, const std::string &newWord) {
    int count = 0;
    size_t i = 0, len = line.size();
    while (i < len) {
        while (i < len && std::isspace(static_cast<unsigned char>(line[i]))) ++i;
        if (i >= len) break;
        size_t start = i;
        while (i < len && !std::isspace(static_cast<unsigned char>(line[i]))) ++i;
        ++count;
        if (count == n) return line.substr(0, start) + newWord + line.substr(i);
    }
    return line; // not replaced if target token missing
}

bool replaceWordAt(const std::string &path, int targetLine, int wordIndex, const std::string &newWord) {
    std::ifstream in(path);
    if (!in) return false;
    std::ofstream out(path + ".tmp");
    if (!out) return false;
    std::string line; int lineNo = 1; bool changed = false;
    while (std::getline(in, line)) {
        if (lineNo == targetLine) {
            std::string nl = replaceNthToken(line, wordIndex, newWord);
            if (nl != line) changed = true;
            out << nl;
        } else {
            out << line;
        }
        if (!in.eof()) out << '\n';
        ++lineNo;
    }
    in.close(); out.close();
    if (!changed) { std::remove((path + ".tmp").c_str()); return false; }
    std::remove(path.c_str());
    return std::rename((path + ".tmp").c_str(), path.c_str()) == 0;
}

Notes and troubleshooting: the code treats punctuation attached to a token (e.g., "word,") as part of that token; strip or split punctuation first if that is undesirable. In-place editing (seek/overwrite) only works safely when the replacement has exactly the same byte length; for variable-length text the stream-and-swap method is safest. For very large files, after modifying the target line the remainder can be copied with stream rdbuf to improve speed. For fixed-length record files (asked by ) random access with seekp is appropriate. Always test on a copy and back up the original before running destructive changes.

Recommended Answers

All 3 Replies

Read the file one word at a time, saving the words in another file except replace the 5th word (or whatever number it is) with the new word. You need two files, an input file and an output file.

Once you have read the target word and written the replacement into the output file, you can read/write the rest of the source file into the output file, in chunks, for efficiency's sake.

dear post example of record replace plz

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.