How may I add a none fixed text to a .txt file? So that I can add text that I just added by hand to the file.
#include <iostream>
#include <fstream>
using namespace std;
int main () {
int x;
ofstream myfile;
myfile.open ("teksts.txt", ios::app);
myfile << x;
myfile.close();
return 0;
}
Also after the file has added the text to the .txt document, how can I pause the run window so It would say "The file has been updated!" and only after I press enter it would exit?
You cannot write a variable to a file, and then replace it later, just like you can't write a variable to cout, and then replace it later.
If you're looking to open a file, write something to it, and then reopen it later, you'll need to use a unique string of text, and then replace that.
myfile << "ABC %%UNIQUE_STRING%% DEF";
Then later...
string uniqueValue = "%%UNIQUE_STRING%%";
string stringObject;
getline(myfile, stringObject);
stringObject.replace(stringObject.find(uniqueValue), uniqueValue.length(), "New Value");
If you're looking for something automatic, everytime the program runs, (since the above will only work once), you'll have to be more clever. One potential option would be to always write to the same character index, and the same amount of characters.
You need to give x a value before you send it to the file ( currently you are just sending junk value)
myfile.open ("teksts.txt", ios::app);
cout << "Please enter text to write to file: ";
cin >> x;
myfile << x;
Just add a statement like cout<< "The file has been updated!";.
To view the output use getchar();
If you want to overwrite the contents each time you open the file, open it in ios::out mode instead. Currently you are using ios::app.
I would also advise to change x into a string, that way you will be able to save text to it.
Related
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;
}
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 am new to this site , and this my first question !
i have a question about fstream function .
fstream f("new.dat",ios::out|ios::in);
fstream is for both input and output , so when we use it like this , and there is a new.dat file before it will output and input both . but it is strange , when i do that , it will output data correctly , but it is unable to input .
i found out if you close it , and reopen it , it will input . why it is like that??
int main()
{
fstream writeFile("newFile.dat", ios::out|ios::in);
char i[3];
char u[3]="HI";
if (!writeFile)
{
cerr << "error" << endl;
}
writeFile << u <<endl;
writeFile >> i;
cout << i << endl;
}
this is my full code , and result is an empty line.
The fstream object has a position in its output file, and since you opened it just for output and input without any position or writing modifiers, that position is at the end of the file. When you output i to the file, writeFile writes i to the file, and then moves its position past i so when you ask it to write more, you don't overwrite i.
You can reset the position to the start of the file with a call to writeFile.seekg(0), which places that internal position at the 0 position in the file (at the start).
If you're curious about stream manipulation, I'd suggest a look at cppreference.com and specifically its documentation on c++'s input and output libraries here.
Couple things going on here:
You can't open a file for reading if it doesn't exist, this includes a file you want to read and write. No file, no open.
Once you manage to open a file, the stream keeps track of where it is in the file. As you read or write, obviously the location moves.
There is only one location marker in the stream, so you can read to where you want to write, then write. Unfortunately this means any further reading will pick up after the write. If that's not what you want, get and store the current location (with tellg) before writing, and seek (with seekg) to the stored location after writing.
This has some problems such as what if the block of data you wish to insert is longer or shorter than the block of data you want to overwrite? The simple solution to this problem is read into buffer, edit buffer, write buffer back to file.
When you open a file and start writing into it, you overwrite whatever was in the file. If you want to add to a file, open with ios::app. This sets the stream's location to the end of the file. I am unaware of any sort of insert that pushes existing data along as you write in new data.
Some simple file handling example code
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
int main()
{
fstream f1("filename", ios::out);
if (f1.is_open())
{
if (f1 << "Hi")
{
cout << "wrote"<<endl;
}
f1.close();
}
fstream f2("filename", ios::out|ios::app);
if (f2.is_open())
{
if (f2 << " there!")
{
cout << "appended"<<endl;
}
f2.close();
}
fstream f3("filename", ios::in);
if (f3.is_open())
{
cout << f3.rdbuf()<< endl;
f3.close();
}
fstream f4("filename", ios::in|ios::out);
if (f4.is_open())
{
f4.seekg(3);
if (f4 << "Fred!")
{
cout << "overwrote"<<endl;
}
f4.close();
}
fstream f5("filename", ios::in);
if (f5.is_open())
{
cout << f5.rdbuf()<< endl;
f5.close();
}
// note the extra ! on the end left over from Hi there! I do not know how
// to get rid of this. I have always just done stuff like this to get around it.
fstream f6("filename", ios::in);
stringstream s1;
string token;
f6 >> token;
s1 << token << " Tim!";
f6.close();
fstream f7("filename", ios::out);
f7 << s1.rdbuf();
f7.close();
// and then moved temp over filename.
fstream f8("filename", ios::in);
cout << f8.rdbuf()<< endl;
f8.close();
}
I've been working on a program that creates and stores information onto files. My only problem that is keeping me from going any farther is the files name. I can manually name the file but I can't use a variable (any would do: number, character anything) for the files name, and for the contents of the file. Here's the 4 lines of code that have driven me up walls for a while now:
ofstream file;
file.open ("txt.txt"); \\I can manually create names, but that's not what I'm after
file.write >> fill; \\I attempted to use a 'char' for this but it gives errors based on the "<<"
file.close();
This is my first time using this site. Sorry in advance.
You may use variables of type strings and ask the user for keyboard input to name your file and fill in contents.
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char** argv) {
string fileName;
string contents;
cout << "What would you like the file name be? : ";
cin >> fileName;
cout << "\nPlease write the contents of the file: ";
cin >> contents;
ofstream file;
file.open(fileName.c_str()); // provide the string input as the file name
if(file.is_open()){ // always check if the program sucessfully opened the file
file << contents << endl; // write the contents into the file
file.close(); // always close the file!
}
return 0;
}
Note that this program will read input from user for contents until it reaches a newline character '\n' or white space ' '. So if you write HELLO WORLD! as the input for contents, it will only read HELLO.
I'll leave how to read the entire line including whitespaces as exercise for you. I also suggest you grab a C++ book and study file input/output.
It really depends? C++11 or C++03?
First create a string:
std::string fname = "test.txt";
In C++11, you can just do:
file.open(fname);
However in C++03, you must:
file.open(fname.c_str());
I'm trying to write up a program that will display the contents of a text file to the screen for a user. Specifically, the text file will be a list of names that the program will read and display each name to the user individually. The user will then either like the name and keep it or dislike the name and remove it.
My dilemma is: if the user elects to keep the name, the program will need to go from reading the file to "writing" (deleting the name) the file and then back to reading the file again! I found the following relevant code on http://www.tutorialspoint.com/cplusplus/cpp_files_streams.htm. It shows that one must use .close() to switch from reading to writing, but this seems funky to a newbie like me. Is there a better way to do it or is the code below just fine?
#include <fstream>
#include <iostream>
using namespace std;
int main ()
{
char data[100];
// open a file in write mode.
ofstream outfile;
outfile.open("afile.dat");
cout << "Writing to the file" << endl;
cout << "Enter your name: ";
cin.getline(data, 100);
// write inputted data into the file.
outfile << data << endl;
cout << "Enter your age: ";
cin >> data;
cin.ignore();
// again write inputted data into the file.
outfile << data << endl;
// close the opened file.
outfile.close();
This is where the file goes from write mode to read mode.
// open a file in read mode.
ifstream infile;
infile.open("afile.dat");
cout << "Reading from the file" << endl;
infile >> data;
// write the data at the screen.
cout << data << endl;
// again read the data from the file and display it.
infile >> data;
cout << data << endl;
// close the opened file.
infile.close();
return 0;
}
Also, I'm having a hard time finding how to read and modify individual characters in the file. I need to do this too, as the file needs to follow a specific pattern, with five names per line and one space between each name (newline at end of fifth name, obviously). Help with this would be appreciated.
Changing things mid-file is complicated.
What I would do is either create a temporary file, write the kept names to that file and replace the original file with this temporary file, (or just store the kept names in a vector and rewrite the file)
try
std::fstream ff("io.txt", std::fstream::in | std::fstream::out);
and fstream::read, fstream::write, fstream::seekg
If the file is small then load it into memory.
Otherwise use fopen with "a+" or "r+" mode and fseek.