Appending string in the middle of a text file - c++

here is my code
#include <string>
#include <iostream>
#include <fstream>
int main(void){
fstream myfile2;
myfile2.open("test2.txt", ios::app);
string checkline;
getline(myfile2, checkline);
int razmer=checkline.length();
string balli="256";
myfile2.seekp(razmer);
myfile2<<balli;
}
test2.txt consists of 2 strings, so it is looks like
Ivanov
Petrov
I want to make from Ivanov -> Ivanov 256. With no touching 2nd string. But my code did not work at all. Thanks in advance.

There's no easy way to edit a text file. The usual solution is to read the whole source file into memory, make your modifications in memory, and then write out all of the file.
In your example where the file seems to be line-based, you could read it line by line and put the lines in a std::vector. Edit the line you want to edit, then loop over the vector and write out the lines.
Note: When writing the file, you open it in write mode, so the file is recreated and looses all old contents.

Related

How can i edit a txt file without deleting the content in c++?

I want to create a database in a txt file and access it and edit certain parts of it using seekp(), but when I open the file to write in it , the program creates a new file deleting the previous one.
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ofstream g;
g.open("text.txt",ios::out);
if(!g.is_open())
cout<<"error";
else {
g.seekp(2);
g.write("apple",5);
}
g.close();
return 0;
}
You'll need a different open mode.
The documentation is quite obscure when it comes to the behavior of ofstream (for all practical purposes, the behavior you observe is by design: it will truncate).
Use fstream with ios_base::in | ios_base::out | ios_base::binary instead.
Unless you're using some encoding where one character is always one, two, or four bytes, you won't be able to consistently do this with a text mode. Also, writing at any seek position before end-of-file won't shift content past the current seek position, it is simply overwritten. So in order to achieve a database-like behavior, you're at least going to need some kind of fixed-size records or an indexing data structure.

So...is there a way to stop files from clearing automatically? (c++)

So i'm making an extremely simple guessing console game and i want to store data permanently in a file (highscore). However everytime i compile the file i'm using empties itself. Is there anyway to stop that?
I've tried a lot of thing which didn't work and i honestly don't know where the problem is. I'm guessing it has to do with the fin and fout but for others it seemed to work
#include <iostream>
#include <fstream>
#include <time.h>
#include <conio.h>
int hs;
//this would be the play_game() function, unrelated to the subject
int main()
{
std::ofstream fout;
fout.open("HS.txt");
std::ifstream fin;
fin.open("HS.txt");
srand(time(NULL));
//menu with 4 options, play, quit, help and highscore (which i'm working on)
fin.close();
fout.close();
}
Don't open your file twice in parallel with two streams. Also, a simple open-for-writing will not truncate your file, but will place you at the start of the file, so you'll be overwriting existing data; see this question. You have to open files with the write mode.
You need to either:
Open your file for both input and output - and without truncating it; see: What does it mean to open an output file as both input and output? , or
Open your file for reading only when your app starts, and open it for writing, and write to it, when it exists (or every once-in-a-while for better resiliency).

How to open file correctly?

Lets assume we have INPUT.TXT file with the following content:
-
-- --
Here we have 16 characters: 5 (-) and 11 ( ). But when I run this code
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ifstream input("INPUT.TXT", ios::ate | ios::binary);
cout << input.tellg(); //returns the number of characters in file
return 0;
}
I get as result 13. I realized that this is due to the fact that the spaces on the first line after the character (-) disappear. So how can I open and read this file so that these spaces do not disappear?
Are you using any kind of advanced text editor that edits or beautify your texts at the time of saving it? I've run the same code on my device and I got the perfect output.
But I tried to save INPUT.TXT using Code::Blocks first. And I found out that Code::Blocks used to remove the trailing spaces during saving.
Use a simple editor that doesn't manipulate your data.

Using getline on html file

I have this assignment to search for certian info in a html file and put the result into text file. I wanted to do it using getline, but somehow it's not working. I have no problems with using getline on text file so I assumed that you cannot use getline on html file. Is that assumption right? How can I convert such file into a text file? Or maybe there is a better/easier solution?Thanks.
Here is the code:(the names of the variables are not in english, I hope it's not a problem)
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
string nazwa_wejsciowego;
string roboczy;
ifstream html;
ifstream txt("wynik.txt");
int main()
{
cout<<"Podaj nazwÄ™ pliku html, z ktorego odczytane maja zostac dane."<<endl;
cin>>nazwa_wejsciowego;
ifstream html(nazwa_wejsciowego, ios::app); //opening the file
if(!html){
cout<<"Otwarcie pliku "<<nazwa_wejsciowego<<" nie powiodlo sie."<<endl;
system("pause");}
//checking if it opende properly
getline(html, roboczy);
cout<<roboczy<<endl;
return 0;}
No, the assumption is not right. HTML is text; the fact that it is in a structured format that can be parsed by a computer to render a webpage is not relevant to read individual characters in the file.
getline may be a suitable approach though, as Steve points out in comments, some HTML pages are "minified" (they have unnecessary whitespace removed to save space and make code harder to copy) and, in such a case, you may end up with just one really big line. It may therefore be more convenient to read in chunks of bytes.

outputting text to a particular line in file using <fstream> header

How can i write some text to a file's particular line using <fstream> header? Is there any function to do that? Thank you.
You can't really do that because the line you write might be longer than then one that exists. So you would clobber a line or have to rewrite the whole file.
If the lines are all exactly the same length, you could do binary writing.
[Edit: the following line was mistakenly added, it's for .NET only]
If you can, use File.ReadAllLines and File.WriteAllLines.
if you want to insert text in line 5 :
1- copy the content of the line 5 to the end of the file on a new file of to a buffer.
2- then write your line. (ater putting cursor in beinnin of line 5)
3- then copy back the lines from the other file.
or, more complicated (not using buffer): (same algorithm as insertion in an array)
you can move all lines atfer the line you want to overwrite to get the eact spae oryour line. then write your line.
for example, you want to write 20 char in line 5.
start by writing 21 char at the end of the file. (if there is a functionthe move charsby 21 characers,i would be easier and perfect).
then put a loop which replace each char with the char in position -21. until un arrive to line 5.
then write your line in line 5.
is that ok ?
The code will look like this:
InputFile.open();
tmpFile.open();
while(InputFile.readline())
{
if (this is where you want the new line)
{
tmpFile.write(newLine);
if(Want to keep the original line)
{
tmpFile.writeLine(oldLine);
}
}
else
{
tmpFile.writeLine(oldLine);
}
}
InputFile.close();
tmpFile.close();
unlink(InputFile);
move tmpFile to InputFile.