This program is "C:\test\program.exe":

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    int choice;
    
    cout<<" Which name to embrace?\n\n";
    cout<<" - 1. Fight Club\n";
    cout<<" - 2. Shawshank Redemption\n";
    cout<<" - 3. Italian Job\n";
    
    cin>> choice;
}

There's also a .txt file there named file.txt, "C:\test\file.txt\". Inside this .txt file is the following:

[Let us embrace those names!]
    
Fight Club =
Shawshank Redemption =
Italian Job =

Now. After "cin>> choice;" in the program, I want there to be code that uses fstream. The program is run and let's say
the user types in "1", referring to "Fight Club". The program will now go inside the .txt file, and put the number "1"
next to "Fight Club =". So, it would be: "Fight Club = 1".

If the program is exited and started again, it would ask the same question: "Which name to embrace," and if
the user again types "1", the program will go inside the .txt file, look for Fight Club and change the line from:
"Fight Club = 1" to "Fight Club = 2". So, each time the program is run and the user types in which name
to embrace, the program will raise the number that stands by the name. How is this done?

P.s I'm using CodeBlocks as a compiler and Windows XP Pro.

Dani AI

Generated

As outlined, the goal is to increment the number after a label in a text file each run. 's append idea just adds lines (not what is wanted), and as correctly feared, trying to use raw seek to overwrite a number breaks once the digit-count changes. A simple, robust pattern is to treat the file as a small key/value list: read it into memory, update the matching line, then write the whole file back (via a temp file + rename to avoid corruption).

Example (safe rewrite approach — reads all lines, finds "Name =", parses the integer, increments, writes back):

#include <fstream>
#include <iostream>
#include <sstream>
#include <vector>
#include <string>
#include <cctype>
#include <cstdio>

static std::string rtrim(std::string s) {
    while (!s.empty() && std::isspace((unsigned char)s.back())) s.pop_back();
    return s;
}

int main() {
    const std::string path = "C:\\test\\file.txt";
    std::ifstream in(path);
    if (!in) return 1;
    std::vector<std::string> lines;
    std::string line;
    while (std::getline(in, line)) lines.push_back(line);
    in.close();

    const std::string target = "Fight Club";
    for (auto &ln : lines) {
        auto p = ln.find('=');
        if (p == std::string::npos) continue;
        std::string name = rtrim(ln.substr(0, p));
        if (name == target) {
            std::istringstream iss(ln.substr(p+1));
            int n = 0;
            if (!(iss >> n)) n = 0;
            ++n;
            ln = name + " = " + std::to_string(n);
            break;
        }
    }

    std::string tmp = path + ".tmp";
    std::ofstream out(tmp);
    for (auto &l : lines) out << l << '\n';
    out.close();
    std::remove(path.c_str());
    std::rename(tmp.c_str(), path.c_str());
}

Notes and alternatives:

  • The rewrite approach is simple and safe; it handles changing digit lengths and is easy to debug.
  • If performance or many concurrent writers matter, use a small DB (SQLite) or keep fixed-width numeric fields (e.g., pad to 6 digits like "000042") so you can compute an in-file offset and overwrite in place with seekp. That demands an initial fixed format and careful padding/formatting.
  • Always check file-open errors, keep a backup when testing, and prefer the temp-file + rename pattern to avoid leaving a truncated file if the program crashes mid-write.

Recommended Answers

All 11 Replies

This is an example of a program which will always add the word 'something' at the end of the file:

#include <iostream>
#include <fstream>

using namespace std;

int main() 
{
	fstream filestr;
		
	filestr.open ("test.txt", fstream::app); 
        // 'app' stands for append
	filestr << "something\n";
	filestr.close();
		
       return 0;
}

You can also use this code with numbers ...

Hope this helps !

Oh, sorry I didn't read your question thoroughly ...

Thanks for the reply mate, but that's not exactly what I had in mind. If I use this program:

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    ofstream myfile;

    myfile.open ("C:\\test.txt", fstream::app); // 'app' stands for append
    myfile << "something\n";
    myfile.close();
}

What I get is a program which constantly adds "something" into the file (as you referred). But, I was looking for a way I think it's called using "seek" to go to the line I want it to go, and once there to output information. Any help there? =)

You could also use structures which you read from the file, everytime the program runs, and write the back to the file when the program has finished ...

But you can also use seekg() ...

You could also use structures which you read from the file, everytime the program runs, and write the back to the file when the program has finished ...

But you can also use seekg() ...

You see the problem with using seekg is that when for example a name f.x. Fight Club goes to "Fight Club = 10", the amount of characters change in the line (they are 14 in "Fight Club = 1" and 15 in "Fight Club = 10"), so the seekg would be bugged when the amount adds an extra character :(

There must be a simple way to do this ?

There must be a simple way to do this ?

Yeah, sure, use structures !

Ok thanks, I'll look at a tutorial on structures, and ask if there are any other quesstions =)

Here's an example of what I mean:

#include <iostream>
#include <fstream>

using namespace std;

int main() 
{
	struct filestruct
	{
		int val_one, val_two, val_three;
	} test;
	
	test.val_one = 12;
	test.val_two = 13;
	test.val_three = 14;
	
	ofstream filestr;
	
	filestr.open ("test.txt");
	
	filestr << test.val_one << endl << test.val_two << endl << test.val_three;
	
	filestr.close();
	
    return 0;
}

This example is only showing you how to write the data to a file ...

You can use a similar method to read it back from the file (using an ifstream object instead of an ofstream object) ...

Is there a command such as seek that counts lines but not characters (So, it would tell the pointer to go to line number 6 f.x.) Is there also a command to select all data in a specific line?

To read a whole line from a file: std::getline(<filename>, <string>);

To count the number of lines in a file you can use the following function:

int countLines(ifstream & file, string filename)
{
	file.close();
	file.open(filename.c_str());
	string line;
	int c = 0;
	
	while(getline(file, line))
		c++; // :-)
	
	file.close();	
	return c;
}

(But you could also write such a function yourself)

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.