Reading from file right after Writing in it - c++

I wanna write in file and then read from it and print the result
Here is my code
#include<iostream>
#include<fstream>
using namespace std;
int main(int argc,char* argv[]){
int x,y;
ofstream fd1(argv[1]);
ifstream fd2(argv[1]);
cin>>x;
fd1<<x;
fd2>>y;
cout<<"just read "<<y<<endl;
fd1.close();
fd2.close();
return 0;
}
What's wrong with it? I input 123 it outputs "just read -1078463800"

Even if you can open both in read & write, this write operation is buffered, which means that it may not be written to disk unless you flush the stream (or you close the file).
Of course the code below works perfectly:
#include<iostream>
#include<fstream>
using namespace std;
int main(int argc,char* argv[]){
int x,y;
ofstream fd1(argv[1]);
cin>>x;
fd1<<x;
fd1.close();
ifstream fd2(argv[1]);
if (fd2.good())
{
cout << "read OK" << endl;
}
fd2>>y;
cout<<"just read "<<y<<endl;
fd2.close();
return 0;
}

The fd2>>y statement is failing because there is nothing to read from the file yet. std::ofstream buffers its output, and you haven't flushed the buffer to the file on disk before trying to then read from the file.
std::ofstream flushes its buffer when:
a new line is written.
its flush() method is called, either directly or when std::flush or std::endl is streamed to it.
Try this:
fd1 << x << flush;
Or:
fd1 << x;
fd1.flush();
On a side note, you really should be checking for errors along the way. The std::ofstream and std::ifstream constructors could fail to create/open the file. The << and >> operators could fail to write/read values. All of those operations can report errors that you can check for. For example:
#include <iostream>
#include <fstream>
int main(int argc, char* argv[])
{
int x, y;
std::ofstream fd1(argv[1]);
std::ifstream fd2(argv[1]);
if (!fd1.is_open())
{
std::cout << "cannot create output file" << std::endl;
}
else if (!fd2.is_open())
{
std::cout << "cannot open input file" << std::endl;
}
else if (!(std::cin >> x))
{
std::cout << "invalid input" << std::endl;
}
else if (!(fd1 << x << std::flush))
{
std::cout << "cannot write to output file" << std::endl;
}
else if (!(fd2 >> y))
{
std::cout << "cannot read from input file" << std::endl;
}
else
{
std::cout << "just read " << y << std::endl;
}
return 0;
}
Alternatively:
#include <iostream>
#include <fstream>
int main(int argc, char* argv[])
{
int x, y;
std::ofstream fd1;
std::ifstream fd2;
fd1.exceptions(std::ofstream::failbit);
fd2.exceptions(std::ifstream::failbit);
std::cin.exceptions(std::ifstream::failbit);
try
{
fd1.open(argv[1]);
fd2.open(argv[1]);
std::cin >> x;
fd1 << x << std::flush;
fd2 >> y;
std::cout << "just read " << y << std::endl;
}
catch (const std::ios_base::failure &e)
{
std::cout << "error! " << e.what() << std::endl;
}
return 0;
}

Related

C++ function unable to another function and ends automaticly

So I was making a file editor using c++ and it has 3 functions and it needs to call each other to work properly.But When code tries to call other functions it end abnormly .
I tried changing the order of functions but it does nothing.It will compile properly without warnings
it needs output the contents of the file.
#include <iostream>
#include <fstream>
#include <bits/stdc++.h>
#include <string>
#include <iomanip>
#include <unistd.h>
#include <sstream>
using namespace std;/* std */
/* data */
char buffer;
std::string fname;
int reader(){
std::ifstream readfile;
readfile.open(fname.c_str());
readfile>>buffer;
std::cout << buffer<< '\n';
int write();
}
int options(){
cout << "************************"<< '\n';
cout << "* Starting File editor *"<< '\n';
cout << "************************"<< '\n';
cout << "* Enter Filename *"<< '\n';
cin >>fname;
cout << "Opening File"<<fname<< '\n';
int reader();
std::cout << buffer<< '\n';
}
int write(){
cout << "writing to file " << '\n';
std::ofstream writefile;
writefile.open(fname.c_str());
writefile<<buffer;
cout << "writing done " << '\n';
}
int main()
{
/* code */
options();
return 0;
}
options() is not calling reader(), and reader() is not calling write(). In both cases, you are simply declaring functions, not actually calling them.
int reader(){
...
int write(); // <-- a declaration, not a call!
}
int options(){
...
int reader(); // <-- a declaration, not a call!
...
}
int main() {
...
options(); // <-- a call, not a declaration!
..
}
Try this instead:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
/* data */
char buffer;
std::string fname;
int reader(){
cout << "opening file " << fname << '\n';
std::ifstream readfile(fname.c_str());
readfile >> buffer;
std::cout << buffer << '\n';
}
int write(){
cout << "writing to file " << '\n';
std::ofstream writefile(fname.c_str());
writefile << buffer;
cout << "writing done" << '\n';
}
int options(){
cout << "************************"<< '\n';
cout << "* Starting File editor *"<< '\n';
cout << "************************"<< '\n';
cout << "* Enter Filename *"<< '\n';
cin >> fname;
reader();
write();
}
int main() {
/* code */
options();
return 0;
}
In addition to the comments above about calling the functions, it seems like it would be good to initialize buffer as a char array as shown below:
#include <iostream>
#include <fstream>
//#include <bits/stdc++.h>
#include <string>
#include <iomanip>
#include <unistd.h>
#include <sstream>
using namespace std;/* std */
/* data */
char buffer[]{"Short test"};
std::string fname;
void write(){
cout << "writing to file " << '\n';
std::ofstream writefile;
writefile.open(fname.c_str());
writefile<<buffer;
cout << "writing done " << '\n';
}
void reader(){
std::ifstream readfile;
readfile.open(fname.c_str());
readfile>>buffer;
std::cout << buffer<< '\n';
write();
}
void options(){
cout << "************************"<< '\n';
cout << "* Starting File editor *"<< '\n';
cout << "************************"<< '\n';
cout << "* Enter Filename *"<< '\n';
cin >>fname;
cout << "Opening File"<<fname<< '\n';
reader();
std::cout << buffer<< '\n';
}
int main()
{
/* code */
options();
return 0;
}
You can declare functions(not compulsory in your case) after all #include statements like:
int reader();
int write();
int options();
You call write function as write(); reader function as reader();
Since functions are not returning anything you could change int reader() to void reader(), int write() to void write() and so on. Keep main as int main() though.

Reverse stack into file

I need to create a program that reads a file, pushes the content into a stack, then writes that content in reverse to another file. I don't understand why my file isn't being found or outputting. Here is my code:
#include "stdafx.h"
#include <iostream>
#include <stack>
#include <fstream>
#include <string>
int main() {
std::stack<char>charStack;
std::fstream file;
std::fstream revFile;
std::string fileName;
std::cout << "Enter the name of the file you want to open." << std::endl;
std::cin >> fileName;
file.open(fileName);
std::cout << "Adding input from file to stack." << std::endl;
char ch;
file >> std::noskipws;
while (file >> ch) {
std::cout << ch;
charStack.push(ch);
}
file.close();
revFile.open("newFile.txt");
std::cout << std::endl;
std::cout << "Reversing stack and writing to file." << std::endl;
while (!charStack.empty()) {
char i = charStack.top();
revFile << i;
charStack.pop();
}
revFile.close();
revFile.open("newFile.txt");
std::cout << "Here is the original file reversed." << std::endl;
std::string line;
if (revFile.is_open()) {
while (std::getline(revFile, line)) {
std::cout << line;
}
revFile.close();
}
else std::cout << "Unable to open file" << std::endl;
revFile.close();
return 0;
}
I'm unsure if I need to add an empty .txt file to write to or if this should generate one for me. Any help would be appreciated.
You need to change the file opening statements to be:
revFile.open("newFile.txt",ios::out); //for output
and
revFile.open("newFile.txt",ios::in); //for input
other than that, you just need to correct this line to get a correct printing of the file contents after reversing.
std::cout << line;
Make it:
std::cout << line << "\n";

ifstream ofstream on mac

I'm trying to read in a random file (on mac-xcode) and determine the instances of the letter k in the document. Then print the number as an outout file. My problem is that the outfile isn't being written and the nums_k is coming back as 0. I'm not sure if the ifstream is working incorrectly or the ofstream need a different filename established. Here's my source code.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream infile("Users/bryanmichaelnorris/documents/extra credit assignment.docx");
string line;
int numks = 0;
while (getline(infile,line)) {
int x = 0;
for (std::string::iterator it=line.begin(); it!=line.end(); ++it) {
if (line[x] == 'k') {
numks++;
}
x++;
}
}
infile.close();
ofstream outfile("number of k's.docx");
outfile << "There are " << numks << " K's in the file." << endl;
outfile.close();
return 0;
}
Added validations for the opened files.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
const char * csInputFileNane="Users/bryanmichaelnorris/documents/extra credit assignment.docx";
ifstream infile(csInputFileNane);
if (!infile.is_open()) {
cerr << "Cannot open file \""<<csInputFileNane<<'"'<<endl;
return -1;
}
string line;
int numks = 0;
while (getline(infile,line))
{ int x = 0;
for (std::string::iterator it=line.begin(); it!=line.end(); ++it) {
if (line[x] == 'k')
{
numks++;
}
x++;
}
}
infile.close();
const char *csOutFileName="number of k's.docx";
ofstream outfile(csOutFileName);
if (!outfile.is_open()) {
cerr << "Cannot open file \""<<csOutFileName<<'"'<<endl;
return -1;
}
outfile << "There are " << numks << " K's in the file." << endl;
outfile.close();
return 0;
}

Handling exception(s) with two file stream in C++

I'm building a program that handles input file and output file, with Visual Studio 2012.
I implemented like this:
ifstream inputFile;
ofstream outputFile;
inputFile.exceptions ( ifstream::failbit | ifstream::badbit );
try
{
// some codes here
inputFile.open(inputFileName.c_str());
cout << "Input file opened" << endl;
outputFile.open(outputFileName.c_str());
cout << "Output file opened" << endl;
}
catch (ifstream::failure e)
{
cerr << "Failed to open input file" << endl;
return -1;
}
catch (ofstream::failure e)
{
cerr << "Failed to open output file" << endl;
return -1;
}
And a compile error occurs:
error C2312: 'std::ios_base::failure' : is caught by 'std::ios_base::failure' at line 248
How do I implement try-catch with two sources of exception?
Your problem is that ifstream::failure and ofstream::failure are the same type (inherited to both of them from ios_base),
Since it is the same exception, the compiler complains.
BTW you should catch by const reference to avoid unneeded copies.
As you can see, the types of the exceptions thrown are the same. But, as your checking is done so near the opening of the file, you can do it without exceptions, no? like:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
string inputFileName { "/notexists" };
string outputFileName { "/notexistsandprobablynotwritable" };
ifstream inputFile { inputFileName };
if( !inputFile ) {
cerr << "Failed to open input file" << endl;
return -1;
}
cout << "Input file opened" << endl;
ofstream outputFile { outputFileName };
if( !outputFile ) {
cerr << "Failed to open output file" << endl;
return -1;
}
cout << "Output file opened" << endl;
}
Or, if you really need the exceptions, you can throw different exceptions yourself, at the open site:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
template<typename Stream, typename Exception = typename Stream::failure>
void try_open(Stream& s, string filename) {
s.open(filename);
if( !s )
throw Exception( string("cannot open ")+filename );
}
struct input_exception: ifstream::failure { input_exception(const string& s): ifstream::failure(s) {} };
struct output_exception: ofstream::failure { output_exception(const string& s): ofstream::failure(s) {} };
int main() {
string inputFileName { "/notexists" };
string outputFileName { "/notexistsandprobablynotwritable" };
try {
ifstream inputFile;
try_open<ifstream, input_exception>(inputFile, inputFileName);
cout << "Input file opened" << endl;
ofstream outputFile;
try_open<ofstream, output_exception>(outputFile, outputFileName);
cout << "Output file opened" << endl;
} catch(const output_exception& e) {
cerr << "output exception!\n" << e.what() << "\n";
} catch(const input_exception& e) {
cerr << "input exception!\n" << e.what() << "\n";
} catch(const exception& e) {
cerr << "exception!\n" << e.what() << "\n";
}
}

boost::asio blocks std::cout when reading from serial port

I'm using boost::asio to read from a serial port. I continuously read from the serial port and print it out through std::cout. But some strange things happens.
I'm using TimeoutSerial class from here. My code goes like this:
#include <iostream>
#include "TimeoutSerial.h"
using namespace std;
int main(){
TimeoutSerial serial;
serial.open("/dev/ttyACM0", 9600 );
serial.setTimeout(boost::posix_time::seconds(1));
char c = '0';
while(true){
try{
serial.read( &c, 1 );
cout << c;
}catch( std::runtime_error err ){
cout << "Error: " << err.what()<< endl;
}
}
return 0;
}
I get no output and I have no idea why. When I change cout << c; to cout << c << endl; I get the output I want but each character is on a new line which is undesirable.
So can anyone tell me why is this happening?
std::cout is buffered by default, so you need to flush it to display it on your terminal. Using std::endl does this implicitly, as will std::flush(). Change your loop to
while(true) {
try {
serial.read( &c, 1 );
cout << c;
std::flush( std::cout );
} catch ( std::runtime_error err ) {
cout << "Error: " << err.what() << endl;
}
}