I am new to C++ and I am trying to use the seekp function in order to return to the beginning of my binary file when reading. However, the Xcode compiler doesn't seem to recognize the seek function. The error given by the compiler is:
/Users/**/Desktop/Programming/Project/Project/Project.cpp:191:10: No member named 'seekp' in 'std::__1::basic_ifstream >'
What am I doing wrong?
Here is the code:
#include <iostream>
#include <fstream>
using namespace std;
int main(){
ifstream f_in;
f_in.open("Pixmap.bin", ios::binary | ios::in);
ofstream f_out;
f_out.open("Pos.txt", ios::binary);
Handle_File_Errors(f_in, f_out);
Pixel_Counter(f_in);
f_in.seekp(0, ios::beg);
f_in.close();
f_out.close();
}
the Pixel_Counter function is written as follows:
void Pixel_Counter (ifstream &f_in) {
uint null;
int i=0;
for (i=0; !f_in.eof();i++) {
f_in.read((char*)&null, sizeof(null));
}
cout<<i-6<<endl;
}
Finally, the Handle_File_Errors does not do anything with the read function but simply checks if the ifstream and ofstream functioned correctly.
There is no seekp for istream.
You probably meant either seekg, or you wanted to use an ostream instead (which does have seekp).
Judging by your code, you seem to want input from the file, so seekg with your istream is appropriate here.
Bear in mind that ifstream and ofstream are subtypes of istream and ostream respectively.
In an ifstream you should use seekg() instead of seekp(), because you want to set the position for reading and not the position for writing.
ifstream and ofstream have only the one of the two function. An fstream can do both, but beware if it's for reading or writing. This tutorial (especially the section about random access) could be of interest for you.
Related
I'm having a little trouble figuring out how to write this value to a file correctly. I did a little research on the internet and found this article.
http://www.eecs.umich.edu/courses/eecs380/HANDOUTS/cppBinaryFileIO-2.html
#include <fstream>
#include <iostream>
int main()
{
int testVar = 71;
std::ofstream outputFile;
outputFile.open("C:/binary.dat", std::ios::out | std::ios::binary);
outputFile.seekg(0);
outputFile.write(&testVar, sizeof(testVar));
outputFile.close();
}
What I understand from the article is that the first parameter is a void pointer? which means that it will accept any type? But when I'm typing it out, the intelisense says there is no overload and the first parameter takes type char*.
Am I using the wrong header or something from an older C++ version??
Could really use some help here.
Thanks!
I am not familiar with the history of development of the functions. Hence, I can't comment on why the arguments are of type char* and not void*.
To solve your problem...
You can use:
outputFile.write(reinterpret_cast<char*>(&testVar), sizeof(testVar));
Use reinterpret_cast while using istream::read() also.
You really just need to cast it to char* like was said before, but there are other problems with the code.
seekg() is for input streams, and you are writing an output file. If you meant to clear the line, just open the file with trunc.
#include <fstream>
#include <iostream>
int main()
{
int testVar = 71;
std::ofstream outputFile("C:/binary.dat", std::ios::out | std::ios::binary | std::ios::trunc);
outputFile.write((char*)&testVar, sizeof(testVar));
outputFile.close();
}
The first parameter is a char*.
char having size 1 byte signifies byte by byte data and char* signifies a block of data.
Hence when writing raw binary data, the data is passed as a char* and size of the block.
Am I using the wrong header or something from an older C++ version??
No it is not the problem as stated it is char* and not void* that is taken as argument.
NOTE The seekg() member function is for input streams. I think the functionality you needed was seekp()
I read about fstream, etc., a while ago. It says that ifstream is used to read data from a file, while ofstream is used to write data. I want to know that, what is the essence of using ifstream/ofstream if you can just use cin.getline() to fetch the data and cout << to print those?
ifstream: Stream class to read from files
ofstream: Stream class to write to files
Now what is a file?
Files are resources for storing information. For example, a text file.
Now, let's look at an example which explains ofstream.
Look at the following code:
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a file.\n";
myfile.close();
return 0;
}
Here, we are writing something to a file. Writing information you can say.
Now, what is the difference between cin/cout and ifstream/ofstream?
cin is an object of class istream and cout is an object of class ostream. And in fact, we can use our file streams the same way we are already used to using cin and cout, with the only difference being that we have to associate these streams with physical files. Just think that cin/cout is a part of istream/ostream that is used for standard input/output.
Hope it helps a bit.
For more information, you can look at this link:
Input/output with files.
Ifstream()
ifstream() is used to input the file.
ifstream() is fstream() object it is used to input the single character or string or set of character to a file
it inherits the function get(), getline(), read(), etc...
Ofstream()
ofstream() is used to output the file
ofstream() is fstream() object it is used to output the single character or string or set of character from a file
it inherits the function put(), write(), etc...
What is the difference between:
fstream texfile;
textfile.open("Test.txt");
and
ofstream textfile;
textfile.open("Test.txt");
Are their function the same?
ofstream only has methods for outputting, so for instance if you tried textfile >> whatever it would not compile. fstream can be used for input and output, although what will work depends on the flags you pass to the constructor / open.
std::string s;
std::ofstream ostream("file");
std::fstream stream("file", stream.out);
ostream >> s; // compiler error
stream >> s; // no compiler error, but operation will fail.
The comments have some more great points.
Take a look at their pages on cplusplus.com here and here.
ofstream inherits from ostream. fstream inherits from iostream, which inherits from both istream and stream. Generally ofstream only supports output operations (i.e. textfile << "hello"), while fstream supports both output and input operations but depending on the flags given when opening the file. In your example, the open mode is ios_base::in | ios_base::out by default. The default open mode of ofstream is ios_base::out. Moreover, ios_base::out is always set for ofstream objects (even if explicitly not set in argument mode).
Use ofstream when textfile is for output only, ifstream for input only, fstream for both input and output. This makes your intention more obvious.
I'm wondering if there's a C++ way of opening a file and reading the input line by line.
I encountered the following code that accomplishes the task:
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ifstream myfile;
myfile.open ("example.txt");
return 0;
}
I'm encouraged to not use any C functions or commands.
The thing is, my "example.txt" is in the form of a string, and using str.c_str() is a C function, so I guess I have two ways to solve the issue.
Is there another way to read input from a file line by line? Perhaps using something that will accept a string as a parameter for the filepath? Is there a C++ way of doing things? :)
Or, is there another way to convert the string in to a const char *, which is what the myfile.open() function needs?
Many thanks in advance!
EDIT: My lack of practivity and research led me to think c_str() was a C function, and it isn't. My apologies. Since it isn't I have found my answer.
C++11's fstream constructor accepts string. In most cases, you want to use fstream's constructor, rather than .open() - you save one line and one function call.
For reading the file line-by-line, you should use std::getline().
Also note that string::c_str() is still C++ function, not C one, as well as fstream's constructor taking const char *. Most of (if not all, I'm not 100% sure) C standard library function are also included in C++ standard.
Since the issue about str.c_str() is already answered, I'm just gonna add a bit about getting inputs line by line. for example, you wanna take 2 ints input per line, extract them, and put it into a vector.
fstream fs(filename.c_str(), ios_base::in);
string line;
stringstream ss;
int a,b;
vector<int> d;
int numlines;
int i;
for (i = 0; getline(fs, line); i++) {
for (ss.str(line); ss >> a >> b; d.push_back(a), d.push_back(b)) {}
ss.clear();
}
numlines = i;
Hope you get the idea of using getline() and fstream()
It's going to look very similar. You'll want an ifstream instead of an ofstream, you'll want the >> operator, and assuming your file has more than one line, you'll need a loop and the ifstream::feof() function.
Any idea why the following would fail?
std::fstream i(L"C:/testlog.txt", std::ios::binary | std::ios::in);
int test = 0;
i >> test;
fail() is returning true. The file exists and is opened.
I checked
i._Filebuffer._Myfile._ptr
and it is pointer to a buffer of the file so I don't see why it is failing.
You're opening the file in binary mode. The extraction operators were meant to be used with text files. Simply leave out the std::ios::binary flag to open the file in text mode.
If you actually do have a binary file, use the read() function instead.
Edit: I tested it too, and indeed it seems to work. I got this from CPlusPlus.com, where it says:
In binary files, to input and output data with the extraction and insertion operators (<< and >>) and functions like getline is not efficient, since we do not need to format any data, and data may not use the separation codes used by text files to separate elements (like space, newline, etc...).
Together with the description of ios::binary, which simply states "Consider stream as binary rather than text.", I'm utterly confused now. This answer is turning into a question of its own...
The following:
#include <fstream>
#include <iostream>
using namespace std
int main() {
std::fstream i("int.dat" , std::ios::binary | std::ios::in);
int test = 0;
if ( i >> test ) {
cout << "ok" << endl;
}
}
prints "ok" when given a file containing the characters "123". Please post a similar short test that illustrates your code failing.