Why my following code fails to read single integer from file?
It displays "fail() reading" followed by "0".
On linux ubuntu gcc compiler.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ofstream fout2("int_data",ios::binary|ios::out);
int a = 2;
fout2.write((char*)&a,sizeof(a));
int b=0;
ifstream fin2("int_data",ios::binary|ios::in);
fin2.read((char*)&b,sizeof(b));
if(fin2.fail())
cout << "fail() reading" << endl;
cout << b << endl;
}
This could fail for a couple reasons:
Your OS may be protecting you from opening a file that is currently opened for writing
You may not have flushed your data to the file
You can solve both of these by using close before you construct fin2:
ofstream fout2("int_data", ios::binary);
const int a = 2;
fout2.write(reinterpret_cast<const char*>(&a), sizeof(a));
fout2.close();
int b = 0;
ifstream fin2("int_data", ios::binary);
if(!fin2.read(reinterpret_cast<char*>(&b), sizeof(b))) {
cout << "fail() reading" << endl;
}
cout << b << endl;;
Live Example
Related
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;
int main() {
fstream a_file_that_will_be_working_with("storage.txt");
if (a_file_that_will_be_working_with.is_open()) {
cout << "is open";
}
else
{
cout << "is not open";
}
a_file_that_will_be_working_with << "first text" << endl;
a_file_that_will_be_working_with << "second text" << endl;
while (a_file_that_will_be_working_with)
{
// read stuff from the file into a string and print it
string strInput;
a_file_that_will_be_working_with >> strInput;
cout << strInput << '\n';
}
return 0;
}
What have I done wrong?
When I use ifstream to read from a file it works, but it doesnt for fstream, I thought fstream is both ofstream and ifstream combined.
See https://en.cppreference.com/w/cpp/io/basic_fstream for an example.
You need to "rewind" the file to read just written stuff (s.seekp(0);).
I have tried two different while loops. I think they have a similar problem. Neither of them terminate or give any output.
The task is to copy (byte for byte) one file into another. The file does not have to have endlines, nor does it have to be a .txt file (it could be .exe...).
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <iomanip>
using namespace std;
int main(int argc, char *argv[])
{
char c, c1, c2;
ifstream inFile;
ofstream outFile;
inFile.open("blackbird.txt");
if (inFile.fail())
{
cout << "\nThe file was not successfully opened for reading."
<< "\nPlease check that the file currently exists.\n\n";
exit(1);
}
cout << "\nThe file has been successfully opened for reading.\n\n";
outFile.open("blackbird_copy.txt");
if (outFile.fail())
{
cout << "The file was not successfully opened for writing" << endl;
exit(1);
}
cout << "The file has been successfully opened for writing.\n\n";
//outFile << "Hello";
// 1) this loop doesn't terminate. 2) the computer doesn't know what c1 is.
/*
while (inFile.get(c1))
{
outFile << c1;
cout << c1;
}
*/
// This one is no better
/*
while (inFile.good())
{
inFile.get(c);
outFile << c;
}
*/
inFile.close();
outFile.close();
// read contents of blackbird_copy to check our work.
inFile.open("blackbird_copy.txt");
while (inFile.get(c2))
{
cout << c2;
}
cout << endl << endl;
return 0;
}
inFile.get(c1) Reads one character and stores it to c1 if available. Otherwise, leaves ch unmodified and sets failbit and eofbit.
You can use inFile.eof() to check whether the end of the file has been reached.
While compiling this simple code:
#include <fstream>
#include <iostream>
#include <string.h>
using namespace std;
class Example
{
public:
char charo;
int into;
};
int main()
{
Example one,two;
one.charo = 'X'; one.into = 2;
//WRITING
ofstream file;
file.open("my.prx", ios_base::binary);
if(file.good()) file.write((char*)&one, sizeof(Example));
else cout << "ERROR WHILE OPENING FILE" << endl;
file.close();
//READING
file.open("my.prx", ios_base::binary);
if(file.good())
file.read((char*)&two, sizeof(Example));
else cout << "ERROR WHILE OPENING FILE" << endl;
file.close();
//PRINTING
cout << "CHAR: " << two.charo << endl;
cout << "INT: " << two.into << endl;
}
I get this error message:
g++ -o test1 main.c main.c: In function ‘int main()’: main.c:43:7:
error: ‘std::ofstream’ has no member named ‘read’
file.read((char*)&two, sizeof(Example));
How can I solve it?
My next step will be to make a more complicated object to save:
Class Memory{
t_monitor monitors[MAX_MONITORS];
t_status status[MAX_STATUS];
t_observer observers[MAX_OBSERVERS];
Var * first_var;
int tot_observers;
int tot_status;
int tot_monitors;
};
As you can see there is also a list...
ofstream is an output file stream. It's used for output, and can't "read".
Use fstream instead.
Use ifstream to read ostream is used for output.
You can do something like this
std::ifstream fileRead( "my.prx",std::ifstream::binary );
if(fileRead)
fileRead.read((char*)&two, sizeof(Example));
else cout << "ERROR WHILE OPENING FILE" << endl;
fileRead.close();
An [ofstream][1] is output only. One readable way is to use the variables ofstream ofile and ifstream ifile. This way the usage is clear from the declaration and the name. If the code grows, this might be helpful.
Another way would be to use the dual-use fstream, but this can make certain operations ambiguous.
Of course, these days, you're probably better off using some sort of serialization library. First, preferring the one that your company or group already uses, and then, if that one is inadequate, picking a modern lib like Boost or, my fave, Cereal.
I'm trying to open a file using ifstream, but no matter what solutions I find that I've tried, nothing seems to work; my program always outputs "unable to open". Below is my code in its entirety. Any help at all is appreciated!
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char ** argv)
{
string junk;
ifstream fin;
fin.open("somefile.txt");
if(fin.is_open())
{
fin >> junk;
cout << junk;
}
else
{
cout << "unable to open" << endl;
}
fin.close();
return 0;
}
Also, the contents of somefile.txt, which is in the same directory as the created executable is the following:
SOME
FILE
As some commenters have suggested, it could easily be that the file truly doesn't exist, because you're looking for it in the wrong place. Try using an absolute path to the file rather than just assuming it's looking where you expect.
And output a more helpful error message using strerror(errno).
// ...
fin.open("C:\\path\\to\\somefile.txt");
// ...
else
{
cout << "unable to open: " << strerror(errno) << endl;
}
I am trying a reasonably simple program to test binary input/output. I am basically writing a file with a header (string) and some data (doubles). The code is as follows:
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <vector>
#include <iterator>
#include <algorithm>
int main() {
typedef std::ostream_iterator<double> oi_t;
typedef std::istream_iterator<double> ii_t;
std::ofstream ofs("data.bin", std::ios::in);
//-If file doesn't exist, create a new one now
if(!ofs) {
ofs.open("data.bin", std::ios::out|std::ios::binary|std::ios::app);
}
else {
ofs.close();
ofs.open("data.bin", std::ios::out|std::ios::binary|std::ios::app);
}
//-Write a header consisting of length of grid subdomain and its name
///*
const std::string grid = "Header";
unsigned int olen = grid.size();
ofs.write(reinterpret_cast<const char*>(&olen), sizeof(olen));
ofs.write(grid.c_str(), olen);
//*/
//-Now write the data
///*
std::vector<double> data_out;
//std::vector<std::pair<int, int> > cell_ids;
for(int i=0; i<100; ++i) {
data_out.push_back(5.0*double(i) + 100.0);
}
ofs << std::setprecision(4);
std::copy(data_out.begin(), data_out.end(), oi_t(ofs, " "));
//*/
ofs.close();
//-Now read the binary file; first header then data
std::ifstream ifs("data.bin", std::ios::binary);
///*
unsigned int ilen;
ifs.read(reinterpret_cast<char*>(&ilen), sizeof(ilen));
std::string header;
if(ilen > 0) {
char* buf = new char[ilen];
ifs.read(buf,ilen);
header.append(buf,ilen);
delete[] buf;
}
std::cout << "Read header: " << header << "\n";
//*/
///*
std::vector<double> data_in;
ii_t ii(ifs);
std::copy(ii, ii_t(), std::back_inserter(data_in));
std::cout << "Read data size: " << data_in.size() << "\n";
//*/
ifs.close();
//-Check the result
///*
for(int i=0; i < data_out.size(); ++i) {
std::cout << "Testing input/output element #" << i << " : "
<< data_out[i] << " " << data_in[i] << "\n";
}
std::cout << "Element sizes: " << data_out.size() << " " << data_in.size() <<
"\n";
//*/
return 0;
}
The problem is that when I try to write and read (and then print) both the header and the data it fails (I confirmed that it doesn't read the data then, but displays the header correctly). But when I comment out one of the write sections (header and/or data), it displays that part correctly indicating the read worked. I am sure I am not doing the read properly. Perhaps I am missing the usage of seekg somewhere.
The code runs fine for me. However you never check if the file is successfully opened for writing, so it could be silently failing on your system. After you open ofs you should add
if (!ofs) {
std::cout << "Could not open file for writing" << std::endl;
return 1;
}
And the same thing after you open ifs
if (!ifs) {
std::cout << "Could not open file for reading" << std::endl;
return 1;
}
Or something along those lines. Also I do not understand why you check if the file exists first since you do the same whether it exists or not.
This should work
#include <iostream>
using std::cout;
using std::cerr;
using std::cin;
using std::endl;
#include <fstream>
using std::ifstream;
#include <cstdint>
int main() {
ifstream fin;
fin.open("input.dat", std::ios::binary | std::ios::in);
if (!fin) {
cerr << "Cannot open file " << "input.dat" << endl;
exit(1);
}
uint8_t input_byte;
while (fin >> input_byte) {
cout << "got byte " << input_byte << endl;
}
return 0;
}