I'm looking to insert the numbers 7777~7781 at position 6000 while at the same time store the strings contained at position 6001~eof to a temporary data structure. The program runs okay. During the first run, the program stores the strings in a vector, but the position 6000 is never modified. However, during the second run, the position is now modified with the numbers 7777~7781. How can I get through this without having to run the file twice? The file I am trying to modify has a randomly generated integers from (1~9999).
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int main() {
string filename1 = "file1.txt";
char buffer[100];
string str1;
fstream file1;
vector<int> nums(5);
int v = 7776;
file1.open(filename1.c_str(), ios::in | ios::out); //opens file 1
if (file1.fail()) {
cerr << "Failed to open the file: " << filename1 << endl;
return (-1);
}
file1.seekg(30000, file1.beg);
vector<string> nums_after(9999); // 9999 for testing
int i = 0;
// store lines 6001~eof in a temp data structure
while (!file1.eof()) {
i++;
getline(file1, str1);
nums_after[i] = str1;
cout << nums_after[i] << endl;
}
file1.clear();
// insert 7777-7781
file1.seekp(29995, file1.beg);
for (int u = 0; u <= 4; u++) {
v++;
nums[u] = v;
sprintf(buffer, "%d", nums[u]);
file1.write(buffer, 4);
file1.write("\n", 1);
}
file1.clear();
file1.close();
return 0;
}
Aucun commentaire:
Enregistrer un commentaire