I have a function that needs to read a file line by line. It will check that line for a number(a process ID for my process scheduling function). The line is delimited by |. So I read the line in, get the first ID number, and then I want to remove that ID number and delimitor from the line and write that line back to the file. But when I do that the line is written back but it deletes everything below it in the file.

Here is what I have so far:

int selectJob() {
	ifstream input;
	input.open("queues.txt", ifstream::in);	
	int lineNumber = 0;
	string line = "";
	int jobID;

	while (!input.eof()) {
		getline(input, line);

		// Line 1
		if (line.length() != 0) {
                        // This just makes a vector of the split up strings.  Its sloppy, but its old code from another program
			const vector<string> jobs(split(line, "|")); 
			cout << jobs[0] << endl;
			// Remove the job from the queue and rewrite the line to the file
			string newString = line.substr(2,line.length());
			cout << newString << endl;
			ofstream output;
	                output.open("queues.txt", ofstream::out);
			output << newString;

			jobID = atoi(jobs[0].c_str());
			return jobID;

You cannot replace a line in a plain text file like this. You'd have to either
1) Read the whole file into memory, replace the line in memory, then rewrite the whole file or
2) Use an actual database (SQL or similar)

Be a part of the DaniWeb community

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