简体   繁体   中英

c++ how to read and write from a specific line in a textfile?

hi I am trying to read a specific line from a text file update that and put it back to the same line without affecting the other lines in c++ here I am trying to execute the code and values get added when I re-execute it

#include <iostream>
#include <stream>
#include <stdio.h>
#include <string>
#include <stream>

using namespace std;
void stringGen(char num){
ifstream ifile;
ifile.open("example1.txt");
if(ifile) {

int LINE = 5;
string line;
 ifstream myfile1 ("example1.txt");
   for (int i = 1; i <= LINE; i++)
     getline(myfile1, line);

     cout << line<<endl;

 stringstream geek(line);
 int num=0;
 geek>>num;
 if(num<61004){
    num=num+1;
    ofstream MyFile("example1.txt");//
    
    
    MyFile.close(); 
    }


else{
    num=61001;
    ofstream MyFile("example1.txt");//
    MyFile << num;
    MyFile.close(); 
}
}
else{
    int num=61001;
    cout<<num<<endl;
    ofstream MyFile("example1.txt");//
    MyFile << num+1;
    MyFile.close(); 
}


}
int main (){
char num;
stringGen(num);
return 0;  
}

At first, you need to understand, how files, with lines are stored. Simplified, it is a sequence of bytes, one byte after the other. There maybe some special characters in this byte sequence, which people can interprete as the end of a line, eg '\n'. But also other characters or even more than one character is possible:

If you look at the following text.

Hello1
World1
Hello2
World2

it maybe stored in a file like this:

Hello1\nWorld1\nHello2\nWorld2\n

And just because we interprete a '\n' as the end of the line, we can "see" lines in there.

So, if you want to modify a line, then you would need to find the start position of the thing that we interprete as a line in the file, and then modify some bytes.

That can of course only be done, if the length of the "line" will not change. Then you could use "seek" functions and overwrite the needed bytes.

In reality, nobody would do that. Normally, you would read "lines" of the file into some kind of memory buffer, then do the modification there and then write back all lines.

For example, you would define a std::vector and then read all lines, by using std::getline and push_back the lines in the std::vector .

The modifications will be done in the std::vector , and the all data will be written back to the file, overwriting all "old" data.

There are more answers to this question. If you have any more specific question, I will answer again

Some simple example code

#include <iostream>
#include <fstream>
#include <vector>
#include <string>

int main() {

    // Here we will store all lines of the text file
    std::vector<std::string> lines{};

    // Open the text file for reading and check, if it could be opened
    if (std::ifstream textfileStream{ "test.txt" }; textfileStream) {


        // Read all lines into our vector
        std::string oneLine{};
        while (std::getline(textfileStream, oneLine)) {

            // Add the just read line to our vector
            lines.push_back(oneLine);
        }

        // For test purposes, modify the first line
        if (not lines.empty()) lines[0] = "MODIFIED";
    }
    else std::cerr << "\nError: Could not open input text file\n";


    // Write back data
    // Open the text file for writing and check, if it could be opened
    if (std::ofstream textfileStream{ "r:\\test.txt" }; textfileStream) {

        // Iterate over all lines and wriite to file
        for (const std::string& oneLine : lines)
            textfileStream << oneLine << '\n';
    }
    else std::cerr << "\nError: Could not open output text file\n";

    return 0;
}
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <string>
#include <sstream>
using namespace std;
void stringGen(char num){
int count=0;
int a;
string line,check,linex;
string msg="Message_Handler:";
fstream ifile;
ifile.open("sample.txt",ios::in|ios::out);
if(ifile){
while(getline (ifile,line)) {
    if (line.find("Message_Handler:") == 0){
        check=line.substr(16,5);
        count++;
        a=ifile.tellp();
    }
    }
 ifile.close();
 if(count==0){
    int num=61001;
    cout<<num<<endl;
    num=num+1;
    ofstream examplefile ("sample.txt",ios::app);
    examplefile<<"Message_Handler:"<<num;
    examplefile.close();
 }
  if(count==1){
    cout<<check<<endl;  
    stringstream geek(check);
    int num=0;
    geek>>num;
    if(num<61004){
        num=num+1;
        stringstream ss;
        ss << num;
        string nums = ss.str();
        fstream MyFile("sample.txt",ios::in|ios::out);
        MyFile.seekp(a-5);
        MyFile<<nums;
  }
   else{
    int num=61001;
    stringstream ss;
        ss << num;
        string nums = ss.str();
        fstream MyFile("sample.txt",ios::in|ios::out);
        MyFile.seekp(a-5);
        MyFile<<nums;

   }
   }
  }
else{
int num=61001;
cout<<num<<endl;
ofstream MyFile("sample.txt",ios::app);
MyFile <<"Message_Handler:"<< num+1;
MyFile.close(); 
}
}
int main (){
char num;
stringGen(num);
return 0;  
}

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