Adding text and lines to the beginning of a file - c++

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

Related

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

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();

multiple reading from folder

I need to read all files from the folder and write to buffer. All files have the same name except the last portion (file_0000.mdf, file_0001.mdf,....file_9999.mdf). How i can read all the files? testFolder contains all the files. If i go with for_loop,it will start with 0 but my test_files start from 0000 and so on. Also, i need file size of each individual test file. My logic is wrong, but i do not know how to fix it. Some updated code is also given below the first approach.
#include <iostream>
#include <fstream>
#include <string>
int main(){
std::string path="C:\\testFolder\\";
std::string constName="file_";
std::string lastName = ".mdf";
std::fstream InputStream;
std::string fileWithPath;
for (int i=0; i <9999;i++){
fileWithPath=path+constName+std::to_string(static_cast<long long>
(i)+lastName;
InputStream.open(fileWithPath,std::ios::binary);
long InputFileSize= InputStream.tellg();
}
return 0;
}
Short update by using boost/filesystem. Need comments on this approach.
#include <boost/filesystem.hpp>
#include <boost/range/iterator_range.hpp>
std::string SourceFolder="C:\\testFolder\\";
path mDirectory(SourceFolder);
std::cout<<"Directory includes the following files"
if(is_directory(mDirectory)){
for(auto testFile=mDirectory.begin();testFile!=mDirectory.end();testFile++){
std::cout<< testFile->string()<<std::endline;
}
Plain integers doesn't have leading zeros. To get leading zeros you need to use some other way of formatting your file-names. For example by using std::ostringstream and standard I/O manipulators like std::setw and std::setfill:
std::ostringstream oss;
oss << path << constName << std::setw(4) << std::setfill('0') << i << lastName;
fileWithPath = oss.str();
You may use FindFirstFile() and FindNextFile() functions scanning the files in the directory using wildcard, i.e. "C:\Data\file_???.mdf".
Returned WIN32_FIND_DATA will contain also a file size.
Take a look on the complete example "Listing the Files in a Directory".
Once a file is listed, you may read its content with ifstream as usually.

Read all character including the null byte

I want to read out the chrome history from its file. I want to get all characters and null byte that's in that file. The problem I'm facing is that I only get some part of the text that's in the file. I belive it stop due to a null byte or a speical character.
HereĀ“s my code that I have at the moment.
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
int main(){
string str;
std::ifstream in("c:/Users/Petrus/Documents/History"); // I have copy my file into my documents to make sure I'm not interfering with Chrome.
std::stringstream buffer;
if (!in.is_open()){
cout << "Failed to open" << endl;
}
else{
cout << "Opened OK" << endl;
}
buffer << in.rdbuf();
std::string contents(buffer.str());
while (getline(buffer, str))
{
cout << str;
}
in.close();
system("PAUSE");
return 0;
}
If you want to take a look at the chrome history file its located at:
C:\Users\YOUR NAME\AppData\Local\Google\Chrome\User Data\Default -->History
(PS You have to include hidden files to be able to see Appdata.)
Thanks in advance
std::getline() should be used only to read plain text files.
To read arbitrary binary files you should use read(). Additionally, on your operating system you must open binary files using the std::ios::binary flag.

text from a file turned into a variable?

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

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();