Text can not be appended to the file - c++

I want to append text to the file "filename.txt" but the text won't append. I have even set the attribute ios_base::app but it does not work(I have tried deleting the file and starting the program again so that the part where the attribute is added will be run;
ifstream MyReadFile("filename.txt");
ifstream f("filename.txt");
bool exits_and_can_be_opened = f.good();
if (exits_and_can_be_opened) {
cout << "This file already exists";
}
else {
MyWriteFile.open("filename.txt", ios_base::app);
MyWriteFile << "Files can be tricky, but it is fun enough!";
MyWriteFile.close();
}
while (getline(MyReadFile, myText)) {
// Output the text from the file
cout << myText << "\n";
}
MyWriteFile << "This thing was appended";
cout << "This was the final change";

You could open the file for reading and writing, and then use positioning functions to move around in the file or to switch from reading to writing
fstream MyFile("filename.txt");
while (getline(MyFile, myText)) {
// Output the text from the file
cout << myText << "\n";
}
MyFile.clear(); // clear any error
MyFile.seekg(0, ios_base::end); // move to the end of the file
MyFile << "This thing was appended";
The other (maybe simpler) way is to close and reopen the file every time you want to switch from reading to writing. Don't have the same file opened twice simultaneously.

Related

Create two files and copy the content of one file in other and displaying it on the screen[C++]

int main()
{
fstream file;
// Input stream class to
// operate on files.
ifstream ifile("file.txt", ios::in);
// Output stream class to
// operate on files.
ofstream ofile("file2.txt", ios::out | ios::app);
// check if file exists
if (!ifile.is_open()) {
// file not found (i.e, not opened).
// Print an error message.
cout << "file not found";
}
else {
// then add more lines to
// the file if need be
ofile << ifile.rdbuf();
}
string word;
// opening file
file.open("file2.txt");
// extracting words form the file
while (file >> word) {
// displaying content of
// destination file
cout << word << " ";
}
How to create file in this code by the respective names given?
Hopefully I understood your quesiton correctly. If so:
std::ifstream instream("in.txt"); // create input stream
std::ofstream outstream("out.txt"); // create output stream
std::string line;
while (std::getline(instream, line)) // read line by line till eof
{
outstream << line << std::endl; // insert the line into output stream
std::cout << line << std::endl; // print the line to stdout
}

edit: trouble checking if file is empty or not, what am I doing wrong?

Edit: changed my question to be more accurate of the situation
I'm trying to open up a text file (create it if it doesnt exist,open it if it doesnt). It is the same input file as output.
ofstream oFile("goalsFile.txt");
fstream iFile("goalsFile.txt");
string goalsText;
string tempBuffer;
//int fileLength = 0;
bool empty = false;
if (oFile.is_open())
{
if (iFile.is_open())
{
iFile >> tempBuffer;
iFile.seekg(0, iFile.end);
size_t fileLength = iFile.tellg();
iFile.seekg(0, iFile.beg);
if (fileLength == 0)
{
cout << "Set a new goal\n" << "Goal Name:"; //if I end debugging her the file ends up being empty
getline(cin, goalSet);
oFile << goalSet;
oFile << ";";
cout << endl;
cout << "Goal Cost:";
getline(cin, tempBuffer);
goalCost = stoi(tempBuffer);
oFile << goalCost;
cout << endl;
}
}
}
Couple of issues. For one, if the file exist and has text within it, it still goes into the if loop that would normally ask me to set a new goal. I can't seem to figure out what's happening here.
The problem is simply that you are using buffered IO streams. Despite the fact that they reference the same file underneath, they have completely separate buffers.
// open the file for writing and erase existing contents.
std::ostream out(filename);
// open the now empty file for reading.
std::istream in(filename);
// write to out's buffer
out << "hello";
At this point, "hello" may not have been written to disk, the only guarantee is that it's in the output buffer of out. To force it to be written to disk you could use
out << std::endl; // new line + flush
out << std::flush; // just a flush
that means that we've committed our output to disk, but the input buffer is still untouched at this point, and so the file still appears to be empty.
In order for your input file to see what you've written to the output file, you'd need to use sync.
#include <iostream>
#include <fstream>
#include <string>
static const char* filename = "testfile.txt";
int main()
{
std::string hello;
{
std::ofstream out(filename);
std::ifstream in(filename);
out << "hello\n";
in >> hello;
std::cout << "unsync'd read got '" << hello << "'\n";
}
{
std::ofstream out(filename);
std::ifstream in(filename);
out << "hello\n";
out << std::flush;
in.sync();
in >> hello;
std::cout << "sync'd read got '" << hello << "'\n";
}
}
The next problem you'll run into trying to do this with buffered streams is the need to clear() the eof bit on the input stream every time more data is written to the file...
Try Boost::FileSystem::is_empty which test if your file is empty. I read somewhere that using fstream's is not a good way to test empty files.

I Can't print out a file that I wrote on

I have created a function to write some data on a text file, and it works fine. I created another function to read in all the content of the file, and print it out for me! But, it is not working for some reason. Could any one help please?
This is my function:
void myClass::displayFile() {
char line[LINE]; //to hold the current line
file.open("data.txt", ios::app);
//keep reading information from the file while the file is open and has data
while (!file.fail() && !file.eof()) {
int lineSize; //to loope through each line
file.getline(line, LINE);
lineSize = strlen(line);
//loop through the line to print it without delimiters
for (int i = 0; i < lineSize; ++i) {
if (line[i] == ';') {
cout << " || ";
} else {
cout << line[i];
}
}
}
file.close();
file.clear();
if (file.fail()) {
cerr << "Something went wrong with the file!";
}
}
Note: The function compiles and the loop is accessible, but the line string is empty.
This is the writing function:
void myClass::fileWriter() {
file.open("data.txt", ios::app);
file << name << ";" << age << ";" << "\n";
file.close();
file.clear();
}
Silly me, the cause of your problem was staring me right in the face from the beginning, and it's the app open-mode that's the problem. It is to open the file in write mode, which means you can't read from it.
And even if you could read from the file, the cursor is placed ad the end of the file the eofbit flag would have been set inside the first iteration anyway.
If you want to read from a file, then either use std::ifstream which automatically sets the in mode if you don't specify a mode, or you have to explicitly set the in mode when opening.

Trying to manipulate files in c++

When using <fstream> library to open and add a stream to an existing file test.rtf and I use the following lines:
char data[100];
// open a file in write mode.
ofstream outfile;
outfile.open("test.rtf");
if (outfile.is_open()) { cout << "file is open" << endl; }
cout << "Writing to the file" << endl;
cout << "Enter your name: ";
cin.getline(data, 100);
// write inputted data into the file.
outfile << data << endl;
And when reading it by using ifstream, the lines input are displayed correctly. The problem is the output file is not modified and lines I have added are not saved. The question might sound very stupid but it's a problem I could not resolve.
When you << to your file you are just writing to a buffer, not actually "flushing" it to the file itself. If you just close your file you should be fine.
So:
outfile.close()
Also in the future you can flush (actually write from buffer to the file) when you want to write to a file but not close it. .close() flushes then closes for you automatically.

Get the number of data entries in another file?

I need to know if you can easily get the number of data entries in another file and save that number in the original file. Need a program that will process the other file no matter how many entries are in it. Hope that makes any sense.
Your question is very poorly worded but I think you are looking for getline. This function can parse an input file based on the newline character (default behaviour) or based on a user provided delimiter:
int entryCount = 0;
std::string currentLine;
std::ifstream inFile( "in.txt" );
std::ofstream outFile;
if (inFile) // short for inFile.good())
{
while (std::getline( inFile, currentLine))
{
++entryCount;
// Do your processing
}
inFile.close();
outFile.open( "out.txt" );
outFile << "End of file. " << entryCount << " entries read." << std::endl;
outFile.close();
}
else
std::cout << "oops... error opening inFile" << std::endl;