std::string uncomment(std::ifstream& infile)
{
std::fstream outfile;
std::string buffer;
std::string tmp;
while(getline(infile, buffer)) {
if(!(buffer[0] == '#')) {
buffer += tmp;
}
}
return buffer;
}
int main(int argc, char const *argv[])
{
std::string filename = argv[1];
std::ifstream infile(filename);
std::fstream outfile("outfile.txt");
std::string buffer = uncomment(infile);
std::cout << buffer << std::endl;
outfile << buffer << std::endl;
outfile.close();
infile.close();
}
Why this code does not produce a new file "outfile.txt"?
Why this code does not print uncommented string on line 22?
I am not sure what std::fstream does but I think you want to use std::ofstream instead.
Looking quickly at docs your outfile constructor is using the default fstream constructor and you don't specify the mode (http://www.cplusplus.com/reference/fstream/fstream/fstream/)
Have you tried using an ofstream constructor since this is an output file?
To create file (if not exist) with fstream you need to pass std::ios::out as open mode to your fstream constructor. like this
std::fstream outfile("outfile.txt", std::ios::out);
Note : Here you don't specified the path to your desired outfile.txt, so it will be generate in your project directory, make sure you check there.
First of all you need to use std::ofstream object to create output file. Or you need to use something like this
std::fstream fs;
fs.open ("outfile.txt", std::fstream::out);
Related
How to read any format of file(doc, pdf, jpeg)? My version works only with txt so i am not able to properly decompress file.
My function for read from input file:
std::string getDataFromFileToString(std::string &fName)
{
std::string s;
std::ifstream fr(fName, std::ios_base::in | std::ios::binary);
if (!fr.is_open())
{
std::cerr << "File \"" << fName << "\" does not exist\n";
exit(EXIT_FAILURE);
}
char c;
while(fr.get(c))
s.push_back(c);
fr.close();
return s;
}
If it only handles text files correctly, you probably need to open the files in binary mode:
change
std::ifstream fr(fName, std::ios_base::in);
to
std::ifstream fr(fName, std::ios_base::in | std::ios::binary);
and make similar changes to your output file.
I'm writing a simple binary file that must contain the contents of another binary file and a string name of this (another) file at the end.
I found this sample code that uses QByteArray from the Qt library. My question is: is it possible to do the same with std c++ functions?
char buf;
QFile sourceFile( "c:/input.ofp" );
QFileInfo fileInfo(sourceFile);
QByteArray fileByteArray;
// Fill the QByteArray with the binary data of the file
fileByteArray = sourceFile.readAll();
sourceFile.close();
std::ofstream fout;
fout.open( "c:/test.bin", std::ios::binary );
// fill the output file with the binary data of the input file
for (int i = 0; i < fileByteArray.size(); i++) {
buf = fileByteArray.at(i);
fout.write(&buf, 1);
}
// Fill the file name QByteArray
QByteArray fileNameArray = fileInfo.fileName().toLatin1();
// fill the end of the output binary file with the input file name characters
for ( int i = 0; i < fileInfo.fileName().size();i++ ) {
buf = fileNameArray.at(i);
fout.write( &buf, 1 );
}
fout.close();
Open your files in binary mode and copy in "one shot" via rdbuf:
std::string inputFile = "c:/input.ofp";
std::ifstream source(input, std::ios::binary);
std::ofstream dest("c:/test.bin", std::ios::binary);
dest << source.rdbuf();
Then write filename at the end:
dest.write(input.c_str(), input.length());
You can find more ways here.
Yes, refer to fstream / ofstream. You could do it like this:
std::string text = "abcde"; // your text
std::ofstream ofstr; // stream object
ofstr.open("Test.txt"); // open your file
ofstr << text; // or: ofstr << "abcde"; // append text
So I'm writing a function to read a file and put its content into another file. Here's what I've got so far:
void myFile::printWords(string input, string output) {
ifstream file(input.c_str());
ofstream file_out(output.c_str());
string word;
if(!file.is_open())
{
printf("File can't be opened\n");
exit(o);
}
while(file >> word) {
cout<< word << '\n';
}
file.close();
}
Question is how do I proceed with writing to a file?
You don't quite need iostreams to copy files; you just need raw stream buffers. For example, here's a complete copy program:
#include <algorithm> // for std::copy
#include <cstdlib> // for EXIT_FAILURE
#include <fstream> // for std::filebuf
#include <iterator> // for std::{i,o}streambuf_iterator
int main(int argc, char *argv[])
{
if (argc != 3) { return EXIT_FAILURE; }
std::filebuf infile, outfile;
infile.open(argv[1], std::ios::in | std::ios::binary);
outfile.open(argv[2], std::ios::out | std::ios::binary);
std::copy(std::istreambuf_iterator<char>(&infile), {},
std::ostreambuf_iterator<char>(&outfile));
}
rather than doing this on a word to word bassis, which doesn't work weel with whitespaces, you could (if you really waht to use c++) use a char[] dump of the file
std::fstream ifile(input.c_str(), std::ios::in | std::ios::binary | std::ios::ate);
std::fstream ofile(output.c_str(), std::ios::out | std::ios::binary);
if (!(ifile.is_open() && ofile.is_open())) { handle_error(); }
size_t size = ifile.tellg();
char* buffer = new char[size];
ifile.seekg(0, std::ios::beg);
ifile.read(buffer, size);
ofile.write(buffer, size);
ifile.close();
ofile.close();
Still it would make much more sense to use your OS functionality
I have written a program which opens a file then displays line by line its contents (text file)
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main (int argc, char* argv[])
{
string STRING;
ifstream infile;
infile.open(argv[1]);
if (argc != 2)
{
cout << "ERROR.\n";
return 1;
}
if(infile.fail())
{
cout << "ERROR.\n";
return 1;
}
else
{
while(!infile.eof())
{
getline(infile,STRING);
cout<<STRING + "\n";
}
infile.close();
return 0;
}
}
What do I need to add to make the file be read only ?
(infile.open(argv[1]) is where am guessing something goes)
The class ifstream is for reading only so, problem solved. Also, did you really mean to check argc after using argv[1] ?
On the other hand, when you use fstream you need to specify how you want to open the file:
fstream f;
f.open("file", fstream::in | fstream::out); /* Read-write. */
The default mode parameter of open for ifstream class is ios::in. That is
infile.open(argv[1]);
is same as:
infile.open(argv[1], ios::in);
So you are opening the file in read-only mode.
You already open the file for read-only. Your can't write to it if you use ifstream. Even:
infile.rdbuf()->sputc('a');
is guaranteed to fail.
You don't need to do anything as the default value for the openmode is already ios_base::in. So you're already good to go :)
See here for more details: http://en.cppreference.com/w/cpp/io/basic_ifstream/open
How to append text to a text file in C++? And create a new text file if it does not already exist and append text to it if it does exist.
You need to specify the append open mode like
#include <fstream>
int main() {
std::ofstream outfile;
outfile.open("test.txt", std::ios_base::app); // append instead of overwrite
outfile << "Data";
return 0;
}
I use this code. It makes sure that file gets created if it doesn't exist and also adds bit of error checks.
static void appendLineToFile(string filepath, string line)
{
std::ofstream file;
//can't enable exception now because of gcc bug that raises ios_base::failure with useless message
//file.exceptions(file.exceptions() | std::ios::failbit);
file.open(filepath, std::ios::out | std::ios::app);
if (file.fail())
throw std::ios_base::failure(std::strerror(errno));
//make sure write fails with exception if something is wrong
file.exceptions(file.exceptions() | std::ios::failbit | std::ifstream::badbit);
file << line << std::endl;
}
#include <fstream>
#include <iostream>
FILE * pFileTXT;
int counter
int main()
{
pFileTXT = fopen ("aTextFile.txt","a");// use "a" for append, "w" to overwrite, previous content will be deleted
for(counter=0;counter<9;counter++)
fprintf (pFileTXT, "%c", characterarray[counter] );// character array to file
fprintf(pFileTXT,"\n");// newline
for(counter=0;counter<9;counter++)
fprintf (pFileTXT, "%d", digitarray[counter] ); // numerical to file
fprintf(pFileTXT,"A Sentence"); // String to file
fprintf (pFileXML,"%.2x",character); // Printing hex value, 0x31 if character= 1
fclose (pFileTXT); // must close after opening
return 0;
}
You could use an fstream and open it with the std::ios::app flag. Have a look at the code below and it should clear your head.
...
fstream f("filename.ext", f.out | f.app);
f << "any";
f << "text";
f << "written";
f << "wll";
f << "be append";
...
You can find more information about the open modes here and about fstreams here.
You could also do it like this
#include <fstream>
int main(){
std::ofstream ost {outputfile, std::ios_base::app};
ost.open(outputfile);
ost << "something you want to add to your outputfile";
ost.close();
return 0;
}