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
Related
My question is how can I get my console to properly display the contents of fileB based on the below information.
Below is the code I have created for basic file input/output operations. I am trying to copy the content from fileA over to fileB. After this is done I am trying to display the contents of fileB to cout. The code runs and updates the contents of fileB to whatever was stored in fileA. However, the console does not display the new content of fileB. It just shows a blank box.
#include <iostream> // Read from files
#include <fstream> // Read/Write to files
#include <string>
#include <iomanip>
void perror();
int main()
{
using std::cout;
using std::ios;
using std::ifstream;
ifstream ifile; // ifile = input file
ifile.open("fileA.txt", ios::in);
using std::ofstream;
ofstream ofile("fileB.txt", ios::out); // ios::app adds new content to the end of a file instead of overwriting existing data.; // ofile = output file
using std::fstream;
fstream file; // file open fore read/write operations.
if (!ifile.is_open()) //Checks to see if file stream did not opwn successfully.
{
cout << "File not found."; //File not found. Print out a error message.
}
else
{
ofile << ifile.rdbuf(); //This is where the magic happens. Writes content of ifile to ofile.
}
using std::string;
string word; //Creating a string to display contents of files.
// Open a file for read/write operations
file.open("fileB.txt");
// Viewing content of file in console. This is mainly for testing purposes.
while (file >> word)
{
cout << word << " ";
}
ifile.close();
ofile.close();
file.close();
getchar();
return 0; //Nothing can be after return 0 in int main. Anything afterwards will not be run.
}
fileA.txt
1
2
3
4
5
fileB.txt (file is initially a blank text document).
fileB.txt (after code runs)
1
2
3
4
5
ofile will have an internal buffer and if it isn't flushed and you only write a small amount of data (possibly as much as 64kb) then no data will be written to your output file until you call ofile.close() or at the end of main().
Simply move ofile.close() to before file.open("fileB.txt").
This happens because you haven't closed the oFile object before you open the FileB.
ofile.close();
file.open("fileB.txt");
By doing this you will have access to the updated file.
I hope that this helps you.
I'm trying to write some text to a file and then read it using only 1 fstream object.
My question is very similar to this question except for the order of the read/write. He is trying to read first and then write, while I'm trying to write first and then read. His code was able to read but did not write, while my code is able to write but not read.
I've tried the solution from his question but it only works for read-write not write-read.
Here is my code:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream fileObj("file.txt", ios::out|ios::in|ios::app);
// write
fileObj << "some text" << endl;
// read
string line;
while (getline(fileObj, line))
cout << line << endl;
}
The code writes some text to file.txt successfully but it doesn't output any text from the file. However, if I don't write text to the file (remove fileObj << "some text" << endl;), the code will output all text of the file. How to write first and then read the file?
This is because your file stream object has already reached the end of the file after the write operation. When you use getline(fileObj, line) to read a line, you are at the end of the file and so you don't read anything.
Before beginning to read the file, you can use fileObj.seekg(0, ios::beg) to move the file stream object to the beginning of the file and your read operation will work fine.
int main()
{
fstream fileObj("file.txt", ios::out | ios::in | ios::app);
// write
fileObj << "some text" << endl;
// Move stream object to beginning of the file
fileObj.seekg(0, ios::beg);
// read
string line;
while (getline(fileObj, line))
cout << line << endl;
}
Although this answer doesn't qualify for your requirement of "reading and writing a file simultaneously", keep in mind that the file will most likely be locked while being written to.
Here the simple example to write and read the file.
Hope it will help you.
#include<fstream>
using namespace std;
int main ()
{
ofstream fout ("text.txt"); //write
ifstream fin ("text.txt"); // read
fout<<"some text";
string line;
while (fin>> line) {
cout<<line;
}
return 0;
}
I created a data file called program.txt. I need to create code that prints out number of lines and integer values from that program.txt
Heres the text I made
1
35
45
87
9
100
the program.text has these values in it
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
string calc;
int test;
int cool;
int book;
ifstream myfile;
ifstream outof;
myfile.open ("program.txt");
outof.open("program.txt");
if (myfile.fail())
{
cerr<<"Error Opening file"<<endl;
}
if(outof.fail ())
{
cerr<<"Error Opening file"<<endl;
}
while (!myfile.eof ())
{
getline(myfile,calc);
++book;
}
cout <<book<<endl;
while (!outof.eof ())
{
outof<<test;//
cool++;
}
cout<<cool<<endl;
myfile.close();
outof.close();
}
Also after cerr I tried exit (1) and it said exit was not defined.
I am new to this any help would be greatly appreciated. Thanks This is C++ btw.
The problem is that you are using ifstream, which stands for INPUT file stream. You want to use ofstream, which is OUTPUT file stream. You cannot write to an input file stream, hence why the << operator is not defined.
Also, rather than using exit(1) after your errors, you can just return 1; as you are inside your main function. This will terminate the program, returning 1 as the exit code.
If you really want to use exit, you need to #include <cstdlib>.
Your defined input and expected output aren't clearly defined, so I'm not sure what you're trying to do. However, here's a general idea:
Putting the filename in a fstream's constructor will automatically try to open the file for read/write. You dont need to call .open() anymore. Also, you shouldnt be reading and writing to the same file simultaneously if you dont know what you're doing.
std::ifstream myInputFile("program.txt");
std::ofstream myOutputFile("programOut.txt");
Rather than checking myInputFile.fail(), just use the overloaded boolean operator. In depth explanation: ifstream::is_open vs ifstream::fail?
if (!myInputFile) {
//Something went wrong
std::cerr << "Failed to open input file" << std::endl;
return 1;
}
Define your std::string to hold lines as you read them, read all of your input file, and count the lines.
std::string line;
int lineCount = 0;
while (getline(myInputFile,line)) {
++lineCount;
//Do something with 'line'
}
Maybe you'll need to store the lines from your input file so that you can output the count of the lines at the beginning of your output file, you might want to #include <vector> and do something like this:
std::string line;
std::vector<std::string> linesFromFile;
//Read in all lines of the input file and store them in the vector
while (getline(myInputFile, line)) {
linesFromFile.emplace_back(line);
}
//All lines read, good time to close input file
myInputFile.close();
//Print number of lines read
myOutputFile << linesFromFile.size() << std::endl;
//Loop through lines and print them
for (auto &lineFromFile : linesFromFile) {
myOutputFile << lineFromFile << std::endl;
}
//Done outputting, close output file
myOutputFile.close();
I think this should be quite simple, but my googling didn't help so far... I need to write to an existing file in C++, but not necessarily at the end of the file.
I know that when I just want to append text to my file, I can pass the flag ios:app when calling open on my stream object. However, this only let's me write to the very end of the file, but not into its middle.
I made a short program to illustrate the issue:
#include <iostream>
#include <fstream>
using namespace std;
int main () {
string path = "../test.csv";
fstream file;
file.open(path); // ios::in and ios::out by default
const int rows = 100;
for (int i = 0; i < rows; i++) {
file << i << "\n";
}
string line;
while (getline(file, line)) {
cout << "line: " << line << endl; // here I would like to append more text to certain rows
}
file.close();
}
You cannot insert in the middle of the file. You have to copy the old file to a new file and insert whatever you want in the middle during copying to the new file.
Otherwise, if you intend to overwrite data/lines in the existing file, that is possible by using std::ostream::seekp() to identify the position within the file.
You could write to the end and swap lines until it ends up in the right position.
Here's what I had to do.
Here's the test.txt file before:
12345678
12345678
12345678
12345678
12345678
Here's a sample of my program
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
fstream& goToLine(fstream& file, int line){
int charInLine = 10; //number of characters in each line + 2
//this file has 8 characters per line
int pos = (line-1)*charInLine;
file.seekg(pos);
file.seekp(pos);
return file;
}
fstream& swapLines(fstream& file, int firstLine, int secondLine){
string firstStr, secondStr;
goToLine(file,firstLine);
getline(file,firstStr);
goToLine(file,secondLine);
getline(file,secondStr);
goToLine(file,firstLine);
file.write(secondStr.c_str(),8); //Make sure there are 8 chars per line
goToLine(file,secondLine);
file.write(firstStr.c_str(),8);
return file;
}
int main(){
fstream file;
int numLines = 5; //number of lines in the file
//open file once to write to the end
file.open("test.txt",ios::app);
if(file.is_open()){
file<<"someText\n"; //Write your line to the end of the file.
file.close();
}
//open file again without the ios::app flag
file.open("test.txt");
if(file.is_open()){
for(int i=numLines+1;i>3;i--){ //Move someText\n to line 3
swapLines(file,i-1,i);
}
file.close();
}
return 0;
}
Here's the test.txt file after:
12345678
12345678
someText
12345678
12345678
12345678
I hope this helps!
Based on my basic knowledge of Operating systems, I would say it is not possible.
I mean it is not impossible to make an OS that can allow such functionality with current storage technologies, but doing so would always lead to wastage of space in segments.
But I am not aware of any technology that can allow that. Although some cloud-based DataBases do use such kinds of functionally (like inserting content in middle of a file), but they are made specifically for that DBMS software, with very specifically targeted hardware, and they may also have some custom-built kernels to perform such tasks.
Here is my requirement: "I need to show to the user on a Console window, the output of a .txt file which will be modified continuously by a Third party application"
I have this code from cplusplus.com:
// reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line;
ifstream myfile ("test_results.txt");
if (myfile.is_open())
{
while ( myfile.good() )
{
getline (myfile,line);
cout << line << endl;
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
Do I need any sort of time counter to read that file at certain regular intervals of time? Guide me, thanks in advance...
There are two approaches.
Platform-dependent
Use API, like inotify in Linux
Platform-independent
Query fs about file modifications, for example using boost::filesystem
http://www.boost.org/doc/libs/1_52_0/libs/filesystem/doc/reference.html#last_write_time