If I made a program that stores strings on a text file using the "list"-function(#include ), and then I want to copy all of the text from that file and call it something(so I can tell the program to type in all of the text I copied somewhere by using that one variable to refer to the text), do I use a string,double,int or what do I declare that chunk of text as?
I'm making the program using c++ in a simple console application.
Easier explanation for PoweRoy:
I have a text in a .txt file,I want to copy everything in it and then all this that I just copied, I want to call it "int text" or "string text" or whatever.But I don't know which one of those "int","string","double" etc. to use.
To take some pity on you, this is about the simplest C++ program that reads a file into memory and then does something with it:
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
using namespace std;
int main() {
ifstream input( "foo.txt" );
if ( ! input.is_open() ) {
cerr << "could not open input file" << endl;
return 1;
}
vector <string> lines;
string line;
while( getline( input, line ) ) {
lines.push_back( line );
}
for ( unsigned int i = 0; i < lines.size(); i++ ) {
cout << (i+1) << ": " << lines[i] << "\n";
}
}
Broadly speaking, you are talking about the concept of Serialization - storing variable values in permanent storage like a file so you can reload them later. Have a look at that link to broaden your understanding.
Specifically, it sounds like you have arbitrary text in a file and want to refer to it in your program. In that case, string sounds appropriate. Unless the text in the file is intended to represent one single number, that seems most appropriate.
Note that if you have structured data (like a CSV file or XML file), a more complex data structure (e.g. a class, array of classes, etc) might be a better choice.
#include <iostream>
#include <fstream>
#include <string>
int main() {
// Open stream from file
std::ifstream ifs("foo.txt");
// Get file contents
std::string file_contents(
(std::istreambuf_iterator<char>(ifs)),
std::istreambuf_iterator<char>()
);
// Output string to terminal to see that it works
std::cout << file_contents;
}
Related
This question already has answers here:
Read file line by line using ifstream in C++
(8 answers)
Closed 3 years ago.
I cant write a words from a file to an array.
I have tried to use char and strings, but i have problem with both of them.
FILE *file = fopen("films.txt", "r");
string FILMS[500];
while (!feof(file))
{
fscanf(file, "%s", FILMS);
//fgets(FILMS, 500, file);
}
I expect that in each cell there will be a word.
Use the C++ classes and functions to make it easier. Instead of a fixed C style array of exactly 500 films, use a std::vector<std::string>> that will grow dynamically when you put film titles in it.
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
std::vector<std::string> get_films() {
std::ifstream file("films.txt");
std::vector<std::string> FILMS;
if(file) { // check that the file was opened ok
std::string line;
// read until getline returns file in a failed/eof state
while(std::getline(file, line)) {
// move line into the FILMS vector
FILMS.emplace_back(std::move(line));
// make sure line is in a specified state again
line.clear();
}
}
return FILMS;
} // an fstream is automatically closed when it goes out of scope
int main() {
auto FILMS = get_films();
std::cout << "Read " << FILMS.size() << " film titles\n";
for(const std::string& film : FILMS) {
std::cout << film << "\n";
}
}
As I'm not sure why you tried using c style arrays and files, I posted a 'not too elegant' solution like that one, too, hoping it might help. You could always try to make it more dynamic with some malloc (or new), but I sticked with the easy solution for now.
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
void readcpp(const char* fname, std::vector<std::string>& data)
{
std::ifstream file_in(fname, std::ios::in);
if (file_in.is_open())
{
std::string film;
while (std::getline(file_in, film))
{
data.push_back(film);
}
file_in.close();
}
else std::cerr << "file cant be opened" << std::endl;
}
#include <cstdio>
#include <cstdlib>
#include <cstring>
void readc(const char* fname, char data[500][500])
{
FILE* file_in = fopen(fname, "r");
if (file_in)
{
char film[500];
for (unsigned int i = 0; fgets(film, 500, file_in) && i < 500; i++)
{
memcpy(data + i, film, 500);
}
fclose(file_in);
}
else fprintf(stderr, "file cant be opened\n");
}
int main()
{
const char* fname = "films.txt";
char cFilms[500][500];
std::vector<std::string> cppFilms;
readc(fname, cFilms);
readcpp(fname, cppFilms);
return 0;
}
And as the others mentioned before, do not use feof or for that matter, ifstream's eof member function either, for checking wheter you reached the end of file, as it may be unsafe.
Hm, I see a lot of code in answers.
The usage of algorithm will drastically reduce coding effort.
Additionally it is a "more modern" C++ approach.
The OP said, that he want to have words in some array. OK.
So we will use a std::vector<std::string> for storing those words. As you can see in cppreference, the std::vector has many different constructors. We will use number 4, the range constructor.
This will construct the vector with a range of similar data. The similar data in our case are words or std::string. And we would like to read the complete range of the file, beginning with the first word and ending with the last word in the file.
For iterating over ranges, we use iterators. And for iterating of data in files, we use the std::istream_iterator. We tell this function what we want to read as template parameter, in our case a std::string. Then we tell it, from which file to read.
Since we do not have files on SO, I use a std::istringstream. But that's the same reading from a std::ifstream. If you have na open file stream, then you can hand it over to the std::istream_iterator.
And the result of using this C++ algorithms is that we read the complete file into the vector by just defining the varaible with its constructer as a one-liner.
We do similar for the debug output.
#include <iostream>
#include <string>
#include <vector>
#include <iterator>
#include <algorithm>
#include <sstream>
std::istringstream filmFile{ R"(Film1 Film2
Film3 Film4 Film5
Film6
)" };
int main()
{
// Define the variable films and use its range constructor
std::vector<std::string> films{ std::istream_iterator<std::string>(filmFile), std::istream_iterator<std::string>() };
// For debug pruposes, show result on console
std::copy(films.begin(), films.end(), std::ostream_iterator<std::string>(std::cout, "\n"));
return 0;
}
This is my first post and I'm fairly new to C++. I am currently looking for a way to save multiple variables to a file (XML or TXT) so it looks like this:
charactername:George
level:5
I would also like to be able to read these and put them into a variable.
Ex:
std::string characterName = "George";
(but it would read George from the line in the file charactername:George)
I have a total of 68 variables (48 strings, 11 ints, and 9 bools) I want in 1 file.
Does anyone know a way to do this or a tutorial they could point me towards? I have found was to save 1 string to a file, but not multiple variables of different types.
I think you should learn how to use a datafile matrix,
But before that here is some basic file management code for you to try use, you'll be able to read in data and recover it based on a structured layout, when recovering your bool data use an implicit conversion to change from a string.
Here are some basic file operations, this will create a txt file that has data on new lines:
// basic file operations
// writing on a text file
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream myfile ("example.txt");
if (myfile.is_open())
{
myfile << "This is a line.\n";
myfile << "This is another line.\n"; // this will for data onto a new line to be read later.
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
How to recover data, this will put the data into a string array which you can then use to recall data from in your code:
// how to retrieve the data:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line, data_array[67];
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
data_array[i] = line; i++;
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
How to edit data, you'll need to have a function to read in all your variables and rewrite the whole text file as unless each line is exactly the same byte you can not jump directly to it.
To look more into detail you should learn how to use a datafile matrix, here are some nice videos to get you started.:
C++ Tutorial (Reading Rows and Columns from datafile Matrix
Matrix in C++ | Part #1 | simple matrix definition using arrays
I want to display all the text that is in the fille to the output,
I use by using the code below, the code I got up and results posts are just a little out
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
char str[10];
//Creates an instance of ofstream, and opens example.txt
ofstream a_file ( "example.txt" );
// Outputs to example.txt through a_file
a_file<<"This text will now be inside of example.txt";
// Close the file stream explicitly
a_file.close();
//Opens for reading the file
ifstream b_file ( "example.txt" );
//Reads one string from the file
b_file>> str;
//Should output 'this'
cout<< str <<"\n";
cin.get(); // wait for a keypress
// b_file is closed implicitly here
}
The above code simply displays the words "This" does not come out all into output.yang I want is all text in the file appear in the console ..
The overloaded operator>> for char* will only read up to the first whitespace char (it's also extremely risky, if it tries to read a word longer then the buf length you'll end up with undefined behavior).
The following should do what you want in the most simple manner, as long as your compiler supports the rvalue stream overloads (if not you'll have to create a local ostream variable and then use the stream operator):
#include <fstream>
#include <iostream>
int main()
{
std::ofstream("example.txt") << "This text will now be inside of example.txt";
std::cout << std::ifstream("example.txt").rdbuf() << '\n';
}
try something like this
#include <fstream>
#include <iostream>
using namespace std;
int main(){
string line;
ofstream a_file ( "example.txt" );
ifstream myfile ("filename.txt");
if (myfile.is_open()) {
while ( getline (myfile,line) ) {
a_file << line << '\n';
}
myfile.close();
a_file.close();
} else
cout << "Unable to open file";
}
Hope that helps
This is not the best way to read from a file. You probably need to use getline and read line by line. Note that you are using a buffer of fixed size, and you might cause an overflow. Do not do that.
This is an example that is similar to what you wish to achieve, not the best way to do things.
#include <fstream>
#include <iostream>
using namespace std;
int main() {
string str;
ofstream a_file("example.txt");
a_file << "This text will now be inside of example.txt";
a_file.close();
ifstream b_file("example.txt");
getline(b_file, str);
b_file.close();
cout << str << endl;
return 0;
}
This is a duplicate question of:
reading a line from ifstream into a string variable
As you know from text input/output with C++, cin only reads up to a newline or a space. If you want to read a whole line, use std::getline(b_file, str)
I have a text file which already has 40 lines of data . I want to write data just before last two lines in a file. I am newbie to c++. I searched online and found few functions like fseek and seekp, but I am not getting how those those functions to change the lines. Can you please give some pointers for this?
Thank you in advance.
Open your file using a std::ifstream
Read the whole file into a std::vector<std::string> with an entry for each line in the file (you can use std::getline() and std::vector<std::string>::push_back() methods to realize this).
Close the std::ifstream
Change the vector entry at the line index you want to change, or alternatively insert additional entries to the vector using std::vector<std::string>::insert()
Open your file using a std::ofstream
Write the vectors content back to the file (just iterate over the vector and output each entry to the file).
You shouldn't mess around with seek functions in this case; particularly not, if the replacements size changes dynamically.
You say C++, so I assume you mean that and not C. A FIFO comes to mind for this purpose.
$ cat last_two_lines.c | ./a.out
#include <iostream>
#include <string>
#include <deque>
main ()
{
std::deque<std::string> fifo;
while (!std::cin.eof()) {
std::string buffer;
std::getline(std::cin, buffer);
fifo.push_back(buffer);
if (fifo.size() > 2) {
std::cout << fifo.front() << "\n";
fifo.pop_front();
}
}
std::cout << " // LINE INSERTED" << "\n";
while (fifo.size() > 0) {
std::cout << fifo.front() << "\n";
fifo.pop_front();
}
return 0;
// LINE INSERTED
}
I'd like to be able to add lines to the beginning of a file.
This program I am writing will take information from a user, and prep it to write to a file. That file, then, will be a diff that was already generated, and what is being added to the beginning is descriptors and tags that make it compatible with Debian's DEP3 Patch tagging system.
This needs to be cross-platform, so it needs to work in GNU C++ (Linux) and Microsoft C++ (and whatever Mac comes with)
(Related Threads elsewhere: http://ubuntuforums.org/showthread.php?t=2006605)
See trent.josephsen's answer:
You can't insert data at the start of a file on disk. You need to read the entire file into memory, insert data at the beginning, and write the entire thing back to disk. (This isn't the only way, but given the file isn't too large, it's probably the best.)
You can achieve such by using std::ifstream for the input file and std::ofstream for the output file. Afterwards you can use std::remove and std::rename to replace your old file:
#include <iostream>
#include <fstream>
#include <string>
#include <cstdio>
int main(){
std::ofstream outputFile("outputFileName");
std::ifstream inputFile("inputFileName");
outputFile << "Write your lines...\n";
outputFile << "just as you would do to std::cout ...\n";
outputFile << inputFile.rdbuf();
inputFile.close();
outputFile.close();
std::remove("inputFileName");
std::rename("outputFileName","inputFileName");
return 0;
}
Another approach which doesn't use remove or rename uses a std::stringstream:
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
int main(){
const std::string fileName = "outputFileName";
std::fstream processedFile(fileName.c_str());
std::stringstream fileData;
fileData << "First line\n";
fileData << "second line\n";
fileData << processedFile.rdbuf();
processedFile.close();
processedFile.open(fileName.c_str(), std::fstream::out | std::fstream::trunc);
processedFile << fileData.rdbuf();
return 0;
}