简体   繁体   中英

How to read then edit file txt in C++

I know this question was asked here but I didn't find what I was looking for. The best answer I could find currently showed how to add something to a text file.

How could I use fstream to either only read the last number in the text file and read the last string too?

Alternately, how could I simply replace a certain line in the file? eg:

the file would be:

Line 1:NAME

Line 2:4

and the code would read line 1, and assign it to a string, and later on change it, same with the second line

Think of a file as a vector stored on disk. If you want to insert something into that file, you have to move everything past it in order to make room for your new line. Similarly, there's no magic to find a line, without going through a file line by line and finding the end line character for your platform.

In most code, the way this type of thing is handled is to load the entire file into memory, then make your modifications there, and write the entire file back out.

If you know exactly how many fields each line has, as well as how many lines, this will help you create a while loop that will assign the fields to vectors or arrays and extract the value accordingly. Then as Joel suggested, open the file to write and replace the contents with the new data.

code:

#include <fstream>
#include <vector>
#include <string.h> //or <string> depending on you IDE, i use Xcode

using namespace std;

int main () {

   vector <string> a;
   vector <string> b;
   string field1;
   string field2;

   ifstream data;

   data.open("data.txt");

    if (data.fail()) {
        cerr << "Error Opening File!" <<endl;
        exit(1);
    }

    while (data >> field1 >> field2) {
    a.push_back(field1);
    b.push_back(field2);
    }

    data.close();

    return 0;
}

That would be how you read it in, vector a holds field1, vector b holds field2, that means that the next index "1" will hold the next lines values (line2).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM