i was wondering how to use c++ ifstream/ofstream to copy a file and save it as another name.
this is as far as i got. I know how to get the file, its just that i don't know how to copy that file and save it as a different name.
#include<iostream>
#include<fstream>
#include<string>
namespace std;
int main()
{
ofstream
ifstream
cout << "enter your file you want to copy"<< endl;
cin >> input_file_name;
in_file.open(input_file_name);
if (!in_file)
{
cout <<" there is no such file"<<endl;
return 0;
}
cout <<" enter the name you want to save this copy file"<<endl;
cin >> output_file_name;
out_file.open(output_file_name);
if (!out.file)
{
cout<<"file is not available"<<endl;
return 0;
}
in_file.close();
out_file.close();
return 0;
}
rdbuf with overloaded << is standard way to go.
ifstream src;
ofstream dst;
src.open("from", ios::in | ios::binary);
dst.open("toto", ios::out | ios::binary);
dst << src.rdbuf();
src.close();
dst.close();
Copy a file and save it on another file:
#include <fstream>
#include <iostream>
#include <string>
int main(int arc, char* argv[]) {
std::ifstream file1(argv[1]);
std::ofstream file2(argv[2]);
std::string line;
if (file1.good() && file2.good()) {
while (getline(file1, line)) {
file2 << line;
file2 << '\n';
}
}
file1.close();
file2.close();
}
Basically you want to read a character at a time and write said character to the output stream. There's a get() overload which accepts a streambuf output variable that would work. You could also use the example on cplusplus.com rdbuf documentation.
http://www.cplusplus.com/reference/fstream/ofstream/rdbuf/
This code below should give you a sense of what you want to do.
There are few things you should keep in mind, for example:
is the path of the file giving to read is valid?
or do you want to save the data from an output file if that file exists, before pushing new data?.
You could test this code by just creating a file into your desktop or any location, just change the filePath and destinationPath variables then run the code. (c++ 11)
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
vector<string> readFromFile(const char *filePath) {
vector<string> container;
ifstream obj(filePath); // automatically our file would be open
if (obj.is_open()) { // we check anyways
string line = "";
while(getline(obj, line)) {
if (!line.empty()) // prevent us to insert empty line into our vector
container.push_back(line);
}
obj.close(); // close after we finish reading to avoid corruption
}
return container;
}
bool pipingToDestination(vector<string>data, const char *filePath) {
std::filebuf fb; fb.open(filePath,std::ios::out); // open the file
ostream obj(&fb);
if (!data.empty() && fb.is_open()) { // make sure we have some data && the file file is open to write
for (string x: data) { // c++11
obj << x << endl;
}
fb.close();
return true;
}
return false;
}
int main() {
string filePath = "/Users/lamar/Desktop/testFile.txt";
vector<string> data = readFromFile(filePath.c_str());
cout << "File has passed data into container ... \n";
for(string x: data) {
cout << x << endl;
}
cout << "Creating destination file \n";
string destinationPath = "/Users/lamar/Desktop/destFile.txt";
cout << "has piped data into file " << boolalpha << pipingToDestination(data, destinationPath.c_str());
return 0;
}
This is not the only way to do this, but this code should put you on a direction
Related
I have made a Quizlet code to save a word with its translation(in Russian) in csv file.
So, the 'add' and 'read' functions work perfectly but I have been trying to make the 'delete' function remove a line when I give a substring of that line.
update: I am trying to copy all the lines except the one that i wanna delete to a new file and then rename it.
but when the new file is created, it is empty!
ex: in the file, line 1: apple яблоко.
input: apple, and then the entire is being deleted.
here is my code: I just have a problem in void quizlet::DeleteWord()
#include <string>
#include <iostream>
#include <vector>
#include<fstream>
#include <sstream>
#include<cstdlib>
using namespace std;
class quizlet {
private:
std::string filename;
std::vector<std::string> lines;
public:
quizlet(std::string filename) : filename(filename) {}
void AddWord(std::string, std::string);
vector<string> ReadAllWords();
void DeleteWord();
};
void quizlet::AddWord(std::string word, std::string translation) {
cout << "Write a word and its translation separated by a space:" << std::endl;
cin >> word >> translation;
// file pointer
fstream fout;
// opens an existing csv file or creates a new file.
fout.open("words.txt",ios::out | ios::app);
// Insert the data to file
fout <<word<<" "<<translation<<endl;
std::cout << "Saved new card: " << word << "/" << translation << std::endl;
}
vector<string> quizlet::ReadAllWords() {
// File pointer
fstream fin;
// Open an existing file
fin.open("words.txt", ios::in);
// Read the Data from the file
// as String Vector
vector <string> rows;
string line, word, temp;
while (getline(fin, line)) {
cout << line << std::endl;
rows.push_back(line);
stringstream s(line);
}
return rows;
}
void quizlet::DeleteWord() {
string line;
fstream fin;
fstream fout;
fin.open("words.txt", ios::in);
fout.open("new.txt",ios::out | ios::app);
string token;
cin>>token;
vector <string> lines;
while (getline(fin, line)) {
if (line.find(token) != string::npos) {
cout << line << endl;
fin << line << endl;
cout<<"the line has been deleted!";
//remove (line);
}
}
fin.close();
fout.close();
remove("words.txt");
rename("new.txt", "words.txt");
cout << "\nChanges has Successfully been made...... Data Saved\n" << endl;
}
int main() {
auto Quizlet = quizlet("words.txt");
string word, translation;
while (true) {
std::string command;
std::cin >> command;
if (command == "add") {
Quizlet.AddWord(word, translation);
} else if (command == "read") {
Quizlet.ReadAllWords();
}
else if (command == "delete") {
Quizlet.DeleteWord();
}
else {
return 0;
}
}
}
Post-update edit:
My original answer now makes much more sense given what you are trying to do. You should read the whole file in at once, make any additions and deletions in-memory you want, then overwrite the original file with the whole, new, list.
Original answer:
Consider reading the file into memory via a std::map<std::string,std::wstring> instead of a std::vector<std::string> of lines in the file.
Using this approach, adding and deleting a word and its translation is simple.
Adding:
//if-guard only needed if you want to protect against overwriting already-existing words.
auto found_iter = cards.find(word);
if(found_iter == cards.end()) {
cards.insert_or_assign(word, translation);
}
Deleting:
auto found_iter = cards.find(word);
if(found_iter != cards.end()) {
cards.erase(found_iter);
}
Writing it back to the file is as simple as looping over the collection:
for(const auto& [word,translation] : cards) {
fout << word << ' ' << translation << '\n';
}
fout.close();
well, after trying for a long time.
I got this code and it works perfectly with no errors.
thank you all!
#include <string>
#include <iostream>
#include <vector>
#include <fstream>
#include <sstream>
#include <cstdlib>
using namespace std;
class quizlet {
private:
std::string filename;
std::vector<std::string> lines;
public:
quizlet(std::string filename) : filename(filename) {}
void AddWord(std::string, std::string);
vector<string> ReadAllWords();
void DeleteWord(std::string);
};
void quizlet::AddWord(std::string word, std::string translation) {
cout << "Write a word and its translation separated by a space:" << std::endl;
cin >> word >> translation;
// file pointer
fstream fout;
// opens an existing csv file or creates a new file.
fout.open("words.txt",ios::out | ios::app);
// Insert the data to file
fout << word << " " << translation << endl;
std::cout << "Saved new card: " << word << "/" << translation << std::endl;
}
vector<string> quizlet::ReadAllWords() {
// File pointer
fstream fin;
// Open an existing file
fin.open("words.txt", ios::in);
// Read the Data from the file
// as String Vector
vector <string> rows;
string line, word, temp;
while (getline(fin, line)) {
cout << line << std::endl;
rows.push_back(line);
stringstream s(line);
}
return rows;
}
void quizlet::DeleteWord(string token) {
string line;
fstream fin;
fstream fout;
fin.open("words.txt", ios::in);
fout.open("new.txt",ios::out | ios::app);
cin >> token;
vector<string> lines;
while(getline(fin, line)) {
if(line.find(token) == string::npos) {
fout << line << endl;
}
}
fout.close();
fin.close();
remove("words.txt");
rename("new.txt", "words.txt");
cout << "\nChanges has Successfully been made...... Data Saved\n" << endl;
}
int main() {
auto Quizlet = quizlet("words.txt");
string word, translation, token;
while(true) {
std::string command;
std::cin >> command;
if(command == "add") {
Quizlet.AddWord(word, translation);
} else if(command == "read") {
Quizlet.ReadAllWords();
} else if(command == "delete") {
Quizlet.DeleteWord(token);
} else {
return 0;
}
}
}
I want to load data from .txt file to variable and working with them (like calculate). When I open data, I can read them, but I don´t know to work with data.
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
fstream newfile;
string file;
newfile.open("zadanie.txt", ios::in);
if (newfile.is_open()) {
while (getline(newfile, file)) {
cout << file << "\n"; //I GET OUTPUT CORRECTLY
}
newfile.close();
}
else
cout << "Error. \n";
cout << file << "\n"; //HERE IS PROBLEM. OUTPUT IS EMPTY
return 0;
}
I tried global variable, but it not solved. What should I do to correct it? Thanks
What you call "PROBLEM" in the comment is not a problem. file never contains more than a single from the file. The last call to getline will not read a line because there is nothing left in the file when you reach its end. So when you call
std::cout << file;
after that loop, it is to be expected that file is empty. If you want to use the lines later you should store them somewhere, eg in a std::vector<std::string>> :
int main()
{
fstream newfile;
std::vector<std::string> data; // vector to hold all lines
newfile.open("zadanie.txt", ios::in);
if (newfile.is_open()) {
string line; // better name (file->line)
while (getline(newfile, line)) {
cout << line << "\n";
data.push_back(line); // add the line to data
}
newfile.close();
}
else
cout << "Error. \n";
for (const auto& l : data) std::cout << l << '\n';
return 0;
}
I am attempting to take a txt file and create a string from it but I cannot figure out how to make it work.
I have tried to use the getline string function but it does not create a proper string in the way I have used it.
ifstream inFile("somefile.txt");
string mystring;
while (getline(inFile, mystring)) {
cout << mystring << endl;
}
The end goal of my program is to read a .txt file line by line and edit each line so it is 100 char wide. This first part seems to be the only place where I am having an issue at the moment.
This can be due to the stream object could not find or open the file. Try checking if the inFile is good or valid.
#include <iostream>
#include <string>
#include <fstream>
using std::cout;
using std::ifstream;
using std::string;
using std::endl;
int main() {
ifstream inFile("example.txt");
string mystring;
if( inFile ) // or inFile.good()
{
while (getline(inFile, mystring))
{
cout << mystring << endl;
}
}
else
{
cout << "Could not open File\n";
}
return 0;
}
My FILE WONT OPEN HELP
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string input_file_name, output_file_name; //file names
ifstream infile; //input file object
ofstream outfile; //output file object
//prompt user for input file
cout << "Enter the input file name: ";
cin >> input_file_name;
//open input file
infile.open(input_file_name.c_str());
//check if file opened successfully
if (!infile)
{
cout << "Error: Unable to open file" << endl;
cout << "Terminating program...";
return 1;
}
else
{
cout << "Successfully opened file!";
}
return 0;
}
when asked for user input i type filename.txt and it wont display successfuly opened message? why....i have the filename.txt on my pc
First off, pardon my use of 'goto', I just felt like it... Try something like what I have shown below where I check if the file actually opened (save the code stub as "asdf.cpp"). Of course you will have to read the data into an array, but it may be a good place to start.
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main(int argc, char * argv[])
{
string line;
ifstream f("asdf.cpp");
if ( !f.is_open() )
goto error_file_not_open;
while( getline(f, line) )
cout << line << endl;
f.close();
return 0;
error_file_not_open:
cout << "Could not open file" << endl;
return -1;
}
If you want to save and read values from/to file, then try something like this:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
// Write values to a file
const int size = 5;
int values[] = { 1,2,3,4,5,6 };
ofstream myfile("lol.txt");
if (myfile.is_open())
{
for (int count = 0; count < size; count++) {
myfile << values[count] << endl;
}
myfile.close();
}
else {
cout << "Unable to open file";
}
// Write read values from a file
std::ifstream file("lol.txt");
if (file.is_open()) {
std::string line;
while (getline(file, line)) {
cout << line.c_str() << endl;
}
file.close();
}
else {
cout << "Unable to open file";
}
}
I'am afraid that your file is not an ANSI-ASCII encoded text file. May be it is encoded by UTF-8 or the Unicode format. The following code will check that the encode of your file. Just try to run it or you could open the lol.txt by any text editor such as, vscode or notepad++.
It will show the encode format of the file at the right-down corner.
Another way to prevent from this issue is try to save the text file to the ANSC-ASCII format. Hope this will help! ^_^
#include <iostream>
#include <fstream>
using namespace std;
unsigned char UTF8Header[] = {0xef, 0xbb, 0xbf};
unsigned char UNICODEHeader[] = {0xff, 0xfe};
int main()
{
char fileName[] = "lol.txt"; // replace the file with your actual file name.
std::ifstream in;
char buffer[3] = {0};
in.open(fileName, std::ios::in | std::ios::binary);
if (!in.is_open())
{
std::cout << "Error opening file";
return -1;
}
if (!in.eof())
in.read(buffer, 2);
if (!in.eof())
in.read(buffer + 2, 1);
if (buffer[0] == UNICODEHeader[0] && buffer[1] == UNICODEHeader[1])
cout << "The file is encoded by unicode format" << endl;
else if (buffer[0] == UTF8Header[0] && buffer[1] == UTF8Header[1] && buffer[2] == UTF8Header[2])
cout << "The file is encoded by UTF-8 format" << endl;
return 0;
}
I'm writing some simple code that's supposed to read every other character, as well as overwriting their adjacent characters with '?'s in a random text file.
eg.
test.txt contains "Hello World";
after running the program, it'd be "H?l?o?W?r?d"
My code below allows me to read every other character from the text file in the console window, but after the program ends and when I open up test.txt, nothing has been changed. Need help to figure out why...
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
fstream data("test.txt", ios::in | ios::out); //here the test.txt can be any random text file
while (!data.eof())
{
if (!data.eof())
{
char ch;
data.get(ch);
cout << "ch is now " << ch << endl;
}
if (!data.eof())
data.put('?');
}
data.close();
return 0;
}
You forgot to consider that you have 2 streams, istream and ostream.
You need to synchronize the location of these 2 streams to achieve what you want. I modified your code a bit to show what I mean.
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
char ch;
fstream data("test.txt", ios::in | ios::out); //here the test.txt can be any random text file
while (data.get(ch))
{
cout << "ch is now " << ch << endl;
data.seekg(data.tellp()); //set ostream to point to the new location that istream set
data.put('?');
data.seekp(data.tellg()); //set istream to point to the new location that ostream set
}
data.close(); // not required, as it's part of `fstream::~fstream()`
return 0; // not required, as 0 is returned by default
}
You are misusing eof(). Do it like this instead:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream data("test.txt", ios::in | ios::out); //here the test.txt can be any random text file
char ch;
while (data.get(ch))
{
cout << "ch is now " << ch << endl;
data.put('?');
}
data.close();
return 0;
}