C++ Read File being wiped at start of program using ofstream - c++

I'm trying to read a text file and output the contents. It's just I can't seem to find the right method and the ones I've used (including this one), seems to wipe the text file. The code:
std::string Line;
std::ifstream File("Account.txt");
if (File.is_open()) {
while (getline(File, Line)) {
std::cout << Line << std::endl;
}
}
else {
std::cout << "Unable to open File" << std::endl;
}
File.close();
I'm also using:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
I'm using this code (below) every time the program runs to create the file which might be the error, if so can anyone recommend a way to create the file only if it doesn't already exist
std::ofstream File("Account.txt");
File.close();

Your file is being wiped by your file creating code.
std::ofstream File("Account.txt");
File.close();
To create a file without wiping existing contents try this
std::ofstream File("Account.txt", std::ios_base::app);
File.close();

Related

C++ - std::getline() returns nothing

I have a C++ function that reads a .txt file, however, when I run it, std::getline returns nothing. Therefore, the while loop on line 22 does not run.
How do I fix this function to return a vector where each line is a different item in the vector?
The file I am reading from a .txt file that has two lines:
testing
123
Here is my code:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
std::vector<std::string> readf(std::string filename)
{
std::ifstream file(filename);
file.open(filename);
// Check if file is open
if (!file.is_open())
{
std::cout << "Error opening file: " << filename << std::endl;
exit(EXIT_FAILURE);
}
std::vector<std::string> lines;
std::string line;
// Read the file
while (std::getline(file, line))
{
if (line.size() > 0)
lines.push_back(line);
}
return lines;
}
You don't need to invoke file.open(filename); because you already opened the file using the constructor std::ifstream file(filename);.
Invoking file.open(filename); after opening the file using the constructor causes the stream to enter an error state, because the file has not been closed yet.
See The difference between using fstream constructor and open function.

How to use a single fstream for creation, reading and writing a file

I would like to access a file through fstream with the following requirements:
If the files does not exists, it create it
The file can be read (from pos 0)
The file can be (over)written (from pos 0)
Without closing and re-opening the file
ios_base::in seems to disable file creation
ios_base::out seems to disable file reading
Is this possible? How?
#include <iostream>
#include <sstream>
#include <fstream>
#include <cassert>
using namespace std;
int main()
{
auto mode = ios_base::in|ios_base::out;
std::string filePath = "./test.txt";
std::string content1 = "Any content 1";
std::string content2 = "Any content 2";
{
std::remove(filePath.c_str());
}
{// Test creation
// make sure test.txt is missing / does not exists
fstream file(filePath, mode);
assert(file.is_open() && file.good());
file << content1;
}
{ // Test reading & writing
fstream file(filePath, mode);
// read
file.seekg(0);
std::stringstream buffer1;
buffer1 << file.rdbuf();
cout << buffer1.str() << endl;
assert(buffer1.str()==content1);
// write
file.seekp(0);
file << content2;
assert(file.is_open() && file.good());
// read
file.seekg(0);
std::stringstream buffer2;
buffer2 << file.rdbuf();
cout << buffer2.str() << endl;
assert(buffer2.str()==content2);
}
return 0;
}
Run it
Only with fstream I'd say no.
You might want to have something similar with the trunc mode but you'll lose everything if the file exists (which might be a problem, if not go for trunc + out)
The other way is to check if the file exists, if not you create it (whichever way). Then you open with In and Out and do your stuff.
It kind of doesn't make sense to be able to read inside an empty file you just created from the cpp point of view

Adding text and lines to the beginning of a file

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;
}

Writing a string to the end of a file (C++)

I have a program already formed that has a string that I want to stream to the end of an existing text file. All of what little I have is this: (C++)
void main()
{
std::string str = "I am here";
fileOUT << str;
}
I realize there is much to be added to this and I do apologize if it seems I am asking people to code for me, but I am completely lost because I have never done this type of programming before.
I have attempted different methods that I have come across the internet, but this is the closest thing that works and is somewhat familiar.
Open your file using std::ios::app
#include <fstream>
std::ofstream out;
// std::ios::app is the open mode "append" meaning
// new data will be written to the end of the file.
out.open("myfile.txt", std::ios::app);
std::string str = "I am here.";
out << str;
To append contents to the end of files, simply open a file with ofstream (which stands for out file stream) in app mode (which stands for append).
#include <fstream>
using namespace std;
int main() {
ofstream fileOUT("filename.txt", ios::app); // open filename.txt in append mode
fileOUT << "some stuff" << endl; // append "some stuff" to the end of the file
fileOUT.close(); // close the file
return 0;
}
Open your stream as append, new text written to it will be written at the end of the file.
I hope that isn't your whole code because if it is, there's lots of things wrong with it.
The way you would write out to a file looks something like this:
#include <fstream>
#include <string>
// main is never void
int main()
{
std::string message = "Hello world!";
// std::ios::out gives us an output filestream
// and std::ios::app appends to the file.
std::fstream file("myfile.txt", std::ios::out | std::ios::app);
file << message << std::endl;
file.close();
return 0;
}

Creating files in C++

I want to create a file using C++, but I have no idea how to do it. For example I want to create a text file named Hello.txt.
Can anyone help me?
One way to do this is to create an instance of the ofstream class, and use it to write to your file. Here's a link to a website that has some example code, and some more information about the standard tools available with most implementations of C++:
ofstream reference
For completeness, here's some example code:
// using ofstream constructors.
#include <iostream>
#include <fstream>
std::ofstream outfile ("test.txt");
outfile << "my text here!" << std::endl;
outfile.close();
You want to use std::endl to end your lines. An alternative is using '\n' character. These two things are different, std::endl flushes the buffer and writes your output immediately while '\n' allows the outfile to put all of your output into a buffer and maybe write it later.
Do this with a file stream. When a std::ofstream is closed, the file is created. I prefer the following code, because the OP only asks to create a file, not to write in it:
#include <fstream>
int main()
{
std::ofstream { "Hello.txt" };
// Hello.txt has been created here
}
The stream is destroyed right after its creation, so the stream is closed inside the destructor and thus the file is created.
#include <iostream>
#include <fstream>
int main() {
std::ofstream o("Hello.txt");
o << "Hello, World\n" << std::endl;
return 0;
}
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
string filename = "/tmp/filename.txt";
int main() {
std::ofstream o(filename.c_str());
o << "Hello, World\n" << std::endl;
return 0;
}
This is what I had to do in order to use a variable for the filename instead of a regular string.
Here is my solution:
#include <fstream>
int main()
{
std::ofstream ("Hello.txt");
return 0;
}
File (Hello.txt) is created even without ofstream name, and this is the difference from Mr. Boiethios answer.
If you want to create a file with some content and don't need to deal with the ofstream after that you can simply write:
#include <fstream>
int main() {
std::ofstream("file.txt") << "file content";
}
no need to manually close the file, deal with variables, etc. The file is created, written, and closed in the same line.
/*I am working with turbo c++ compiler so namespace std is not used by me.Also i am familiar with turbo.*/
#include<iostream.h>
#include<iomanip.h>
#include<conio.h>
#include<fstream.h> //required while dealing with files
void main ()
{
clrscr();
ofstream fout; //object created **fout**
fout.open("your desired file name + extension");
fout<<"contents to be written inside the file"<<endl;
fout.close();
getch();
}
After running the program the file will be created inside the bin folder in your compiler folder itself.
use c methods FILE *fp =fopen("filename","mode");
fclose(fp);
mode means a for appending
r for reading ,w for writing
/ / using ofstream constructors.
#include <iostream>
#include <fstream>
std::string input="some text to write"
std::ofstream outfile ("test.txt");
outfile <<input << std::endl;
outfile.close();