C++ Changing values from text file [duplicate] - c++

This question already has answers here:
What is the easiest way to parse an INI File in C++? [closed]
(13 answers)
Closed 8 years ago.
I am a c++ beginner and I have a (probably simple) question. So far i have defined several variables:
double Start = 0;
double End = 1;
int Steps = 100;
I want to change these values to a value that I have stated in a text file "paramaters.txt":
x_start = 0
x_end = 10
num_steps = 100
So my c++ needs to read the file and change the double End from 1 to 10. Reading the file can be done with this function:
std::ifstream file("parameters.txt")
I want to define a variable of type std::string, called label. Then i want to read the ’label’ from the file. Using a group of ’if (label == ”value”)’ statements to determine if I'm dealing with the start, end of the number of steps. Within the if-statement, the value of 10 would stand for the end for example.
I hope that someone can help me.
Regards,

It seems you want to read a file for some values. You can do that by reading file line by line and then parsing each line.
For e.g in your case you would separate the line into two words with demiliter as "=".
But often the best way to read file for some values is to use some libraries. Like you can use boost::program options.

Related

How to read in a txt file in c++, if we don't know how many data strings are in it, and how long each row is? [duplicate]

This question already has answers here:
Read file line by line using ifstream in C++
(8 answers)
Closed 5 years ago.
There is an input.txt, with string sorted like this:
Name1 Name2 "number1:number2" "number1:number2"...
.
.
.
NameX NameY "number1:number2" " number1:number2"...
Baically we don't know how much names are in it, and how much "number:number" strings are in a row. The task is to write out the first name in each line, and write out the number of times, when number1 is bigger than number2 in each row.
The thing is, I don't know how should I read in the pairs, without knowing how many are there from them in each row.
Thanks for the help in advance.
edit: My problem is not actually the part where I don't know how long the file is, I can read it in line by line, I don't know how should I read in a row, where I don't know how many strings are.
edit2, exaple: Steven Jack 2:5 6:4 7:2
You could get the seperated elements with a stringstream one by one, and check if it starts with a decimal digit character or not (works only if there isn't any name that starts with a number).
like so:
std::string line; // assuming you got the line
std::stringstream ss(line);
std::string str;
while (ss >> str) {
// use isdigit() to check if it's a decimal digit character or not
if (isdigit(s.at(0))) {
// do something with NUMBERS
// getting the actual numbers from these strings is another problem
} else {
// do something with NAMES
}
}
EDIT : as you said getting lines one by one is not a problem, so the "line" variable in my code assumes that you somehow got a whole line in the memory and works with this line.
EDIT2 : it's not much different if you don't have quotation marks, in this case, you check if the first character is a number or not (btw if any name starts with a number it's gonna be a problem)

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.

C++ append to existing file [duplicate]

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.

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.

How to use regexp to find unique combinations of letters and use them as variables in Matlab?

I have the file names of four files stored in a cell array called F2000. These files are named:
L14N_2009_2000MHZ.txt
L8N_2009_2000MHZ.txt
L14N_2010_2000MHZ.txt
L8N_2009_2000MHZ.txt
Each file consists of an mxn matrix where m is the same but n varies from file to file. I'd like to store each of the L14N files and each of the L8N files in two separate cell arrays so I can use dlmread in a for loop to store each text file as a matrix in an element of the cell array. To do this, I wrote the following code:
idx2009=cellfun('isempty',regexp(F2000,'L\d{1,2}N_2009_2000MHZ.txt'));
F2000_2009=F2000(idx2009);
idx2010=~idx2009;
F2000_2010=F2000(idx2010);
cell2009=cell(size(F2000_2009));
cell2010=cell(size(F2000_2010));
for k = 1:numel(F2000_2009)
cell2009{k}=dlmread(F2000_2009{k});
end
and repeated a similar "for" loop to use on F2000_2010. So far so good. However.
My real data set is much larger than just four files. The total number of files will vary, although I know there will be five years of data for each L\d{1,2}N (so, for instance, L8N_2009, L8N_2010, L8N_2011, L8N_2012, L8N_2013). I won't know what the number of files is ahead of time (although I do know it will range between 50 and 100), and I won't know what the file names are, but they will always be in the same L\d{1,2}N format.
In addition to what's already working, I want to count the number of files that have unique combinations of numbers in the portion of the filename that says L\d{1,2}N so I can further break down F2000_2010 and F2000_2009 in the above example to F2000_2010_L8N and F2000_2009_L8N before I start the dlmread loop.
Can I use regexp to build a list of all of my unique L\d{1,2}N occurrences? Next, can I easily change these list elements to strings to parse the original file names and create a new file name to the effect of L14N_2009, where 14 comes from \d{1,2}? I am sure this is a beginner question, but I discovered regexp yesterday! Any help is much appreciated!
Here is some code which might help:
% Find all the files in your directory
files = dir('*2000MHZ.txt');
files = {files.name};
% match identifiers
ids = unique(cellfun(#(x)x{1},regexp(files,'L\d{1,2}N','match'),...
'UniformOutput',false));
% find all years
years = unique(cellfun(#(x)x{1},regexp(files,'(?<=L\d{1,2}N_)\d{4,}','match'),...
'UniformOutput',false));
% find the years for each identifier
for id_ix = 1:length(ids)
% There is probably a better way to do this
list = regexp(files,['(?<=' ids{id_ix} '_)\d{4,}'],'match');
ids_years{id_ix} = cellfun(#(x)x{1},list(cellfun(...
#(x)~isempty(x),list)),'uniformoutput',false);
end
% If you need dynamic naming, I would suggest dynamic struct names:
for ix_id = 1:length(ids)
for ix_year = 1:length(ids_years{ix_id})
% the 'Y' is in the dynamic name becuase all struct field names must start with a letter
data.(ids{ix_id}).(['Y' ids_years{ix_id}{ix_year}]) =...
'read in my data here for each one';
end
end
Also, if anyone is interested in mapping keys with values try looking into the containers.map class.