C++ append to existing file [duplicate] - c++

This question already has answers here:
How to write to middle of a file in C++?
(3 answers)
Closed 6 years ago.
I'm trying to take data from multiple files and append them into one file using fstream, however whenever I try to output to an existing file using
std::ofstream Out("mushroom.csv", std::ofstream::app);
it outputs to the end of the file, I want it to append to the same line, for example if this is the previous file:
1,2,3,4,5,6,7
8,9,10,11,12,13
I want it to become:
1,2,3,4,5,6,7,a,b,c
8,9,10,11,12,13,c,d,e

You can't. Files don't really have lines, they just store a bunch of characters/binary data. When you have
1,2,3,4,5
6,7,8,9,0
It only looks that was because there is an invisible character in there that tells it to write the second line to the second line. The actual data in the file is
1,2,3,4,5\n6,7,8,9,0
So you can see then end of the file is after the 0 and to get after the 5 you would need to seek into the middle of the file.
The way you can get around this is to read each line of the file into some container and then add your data to the end of each line. Then you would write that whole thing back o the file replacing the original contents.

Related

How can I use C++ to eliminate the BOM in a notepad .txt file? [duplicate]

This question already has answers here:
How can I make Notepad to save text in UTF-8 without the BOM?
(7 answers)
Closed 5 years ago.
I want to read in a .txt file using ifstream fin from library fstream, but there is a BOM at the beginning of the file that is causing problems. Is there a way I can, from inside my C++ program, eliminate the BOM in the .txt file, so that fin can read it without any issues? I know I can manually delete the BOM in the file myself, but I have multiple files I'm working with so this will take a while.
My question is similar to this one here, except this one deals in Java:
How to make Notepad to save text in UTF-8 without BOM?
The answer from korifey is what I am looking for, where they said:
Use PushbackInputStream(in, 3)
Is there something similar I can do in C++ ? It should also be noted that I only have Notepad (not Notepad++), and it is preferable to solve my problem without downloading any new software. I also don't want to change how Notepad itself views BOMs, I just want to physically delete the BOM from my .txt file. The BOM I'm dealing with is the first 8 characters.
This would be easiest by opening the file in binary mode, reading all the data and copying everything but the BOM to a different file, then removing the old file and finally renaming the new file back to the name of the old.

Groovy read file backwards [duplicate]

This question already has answers here:
Tail a file in Groovy
(2 answers)
Closed 6 years ago.
Any groovy way to read a file backwards? Took a look at Reader class, but nothing there seems to help. My use case is mostly finding the last line of a file that matches a condition (regex, contains a string etc.).
Later Edit:
I think this question is not really a duplicate of the tail one. I see tail as more of a 'live' processing of a file. My problem is more into processing big log files (size in tens of GB), so loading whole file into memory is not an option. The file content is static (not updated during processing).
For example, each time an object is updated we log a line saying which user did it and at some later point we need to the last user that generated that update.
Thanks
This worked for me:
String filePath = '/path/to/file'
File file = new File(filePath)
String sample = 'searchSample'
file.text.split('\n').reverse().find {it.contains(sample)}
UPD
Also maybe FileUtils#backWardsRead() will be helpful for you.
This doesn't read the file backwards, but it does process the lines backwards, which I believe lines up with the intended use case of finding the "last line in the file that matches a condition."
import java.util.stream.Collectors
new File('myfile.csv').newReader()
.lines()
.collect(Collectors.toList())
.reverse()
.find { line -> line ==~ myRegex }
This requires Java 8 as it uses the Stream API.

Convert a list (.txt file) into an array form [duplicate]

This question already has an answer here:
c++ how to build a 2D matrix of strings from a .dat file? 5 columns x rows
(1 answer)
Closed 8 years ago.
Say that I have a .txt file with 5000 words one above the other. and I want to convert that list contained in the txt file into this form:
{"word1, "word2", "word3" ....."word5000"}
So that way I can use it as an array for C++.
Is there a way to do that? Any method is welcome , as long as it is an automated process. Thanks for reading!
Use a vector instead of an array. Using it, the task looks something like this:
std::ifstream in("words.txt");
std::vector<std::string> words{ std::istream_iterator<std::string>(in),
std::istream_iterator<std::string>() };
Now the word that was on the first line of the file is in words[0], the second in words[1], and so on.
Note: if a line contains more than one word, this will read them as separate words. If you want the entire contents of a line treated as a single word, see the answers to a previous question specifically about how to do that.

C++: Get line by the line number [duplicate]

This question already has answers here:
Moving the file cursor up lines?
(3 answers)
C++ Get Total File Line Number
(7 answers)
Closed 8 years ago.
Is there a fast way to get a line from a text file by the line number? If I wanted only line 20 is there anything that will allow me to do something like get line 20? I know getline(in, line) reads in each line one at a time but I rather not call getline 20 times to get the 20th line.
Thanks!
No, there is no fast and magical method.
Background
Text file records are variable length. Each text line may vary in the number of characters. Fixed records are easy since their length is known.
To find the Nth record, you have to find the beginnings or endings of the text records. This is often performed by searching for a newline character. Still tedious.
Converting to Random Access
If the data is requested many times, a map or dictionary of the record line number and its position would be handy. Use the line number, retrieve the file postion, then set the file pointer to the given position.
Memory mapped file
If there is enough memory, the file could be read and stored in memory.
However, one still has to search for the newlines and count them to find line X.
Summary
There is no fast method to find the start of a text line in a file, the first time. In any case, the text must be searched for the newlines and the newlines counted.
There are methods to speed up the process, but those involve reading the file one or more times. The mapping of line numbers to file positions is fast but requires an initial scan. Loading the file into memory (memory mapping) requires reading the file into memory (first read) then searching the memory; also, the OS may only load portions of file that are requested and not the entire file.
No, you have to use a loop that will advance to the next line twenty times.
The reason it is not possible to do what you want is the way the file is structured: It's a sequence of bytes, and a new line is just another byte (or a sequence of two bytes, by the Windows convention).

c++ write to the beginning of current line of file [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I created a ofstream file.
How can I write to the beginning of current line on my file?
For example: I write:
a b c d e f
and now I want to add to the beginning the number of my letters (6) like this:
6 a b c d e f
You have to read the whole file in a byte array.
Then you write your "prefix" followed by you write the byte array to a tmp file.
Finally you have to delete the original file and rename the tmp file.
If you want to write at the beginning of an arbitrary line then you should read the whole file in an array of arrays of bytes, append your prefix to the line you want to edit and finally overwrite the original file.
HINT:-
If it is a text file then the best solution would be to flush the old contents into a temporary location, write what you need and append the old contents
Files are pretty static and don't support adding characters anywhere except at the end. If you need to add characters elsewhere, you need to rewrite the file. Also, files don't really have a concept of lines.
What you could do is recording the position of the file at the beginning of the line (using file.tellp()), write a couple of placeholders (e.g., spaces), and then the rest of the line. Once the line is complete, you'd reposition the write position (using file.seekp()) and overwrite some of the placeholders.
Personally, I wouldn't do anything like that! Instead, I would format the line into a std::ostringstream and, once completed write the line start information followed by the firmatted line (obtained from the std::ostringstream using str()). Well, ideally I'd write the information in one sequence directly to the file if it is readily available.
Files are essentially a stream of bytes that start at a specific location. The only way to insert new data in the front (or in the middle) of a file is to move the data that is after it. Since you are expecting to rewrite the first line, that would mean you would need to read the entire file, prepend your new data, and write out the entire (new) file over the existing one. You can do this with a single std::fstream object, but you will need to reset the file cursor to the beginning after you read the file. It would be more clear to read the file in using an std::ifstream object and then to overwrite the file with an std::ofstream object.
I have on my code:
file << args;
-->here I want to add to the beggining of this line a new argument.. (This argument has information of args But I must write args and after I have the information for the argument)
file << endl;