file created but no contents
Sep 12, 2017 at 6:28am UTC
The code inputs values but when i go and open the dat file created with notepad its shows nothing
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
int rno,marks;
char ch;
fstream f1("mark.dat" ,ios::out|ios::binary);
f1.open("mark.dat" );
do
{
cout << "Enter roll number" ;cin >> rno;f1 << rno;
cout << "\nEnter marks" ;cin >> marks;f1 << marks;
cout << "\nDo you want to continue?(y/n)" ;cin >> ch;
cout << endl;
}while ((ch=='y' )||(ch=='Y' ));
f1.close();
return 0;
}
Sep 12, 2017 at 6:46am UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
#include<iostream>
#include<fstream>
int main()
{
const char file_name[] = "mark.dat" ;
{
int rno, marks;
char ch;
std::ofstream file(file_name) ; // open file for output
do
{
std::cout << "\nEnter roll number: " ;
std::cin >> rno;
std::cout << "\nEnter marks: " ;
std::cin >> marks;
if ( std::cin ) // if there is no input failure
{
file << rno << ' ' << marks << '\n' ;
std::cout << "\nDo you want to continue?(y/n)" ;
std::cin >> ch;
}
} while ( std::cin && ( (ch=='y' ) || (ch=='Y' ) ) ) ;
} // file object goes out of scope; the file is automagically flushed and closed
// verify by dumping the contents of the file on stdout
std::cout << std::ifstream(file_name).rdbuf() ;
}
Sep 12, 2017 at 11:26am UTC
In the original code, the file is opened twice. The second attempt will fail, meaning the stream is no longer useable.
1 2 3 4 5 6 7
cout << boolalpha; // print true / false as words instead of 1 / 0
fstream f1("mark.dat" , ios::out | ios::binary);
cout << "open: " << f1.is_open() << " fail: " << f1.fail() << '\n' ;
f1.open("mark.dat" );
cout << "open: " << f1.is_open() << " fail: " << f1.fail() << '\n' ;
Output:
open: true fail: false
open: true fail: true
It is usually simpler to use
i fstream
for input and
o fstream
for output, rather than specifying the mode separately. Also, binary mode is not appropriate here.
Instead of
1 2
fstream f1("mark.dat" ,ios::out|ios::binary);
f1.open("mark.dat" );
just put
Topic archived. No new replies allowed.