Hey guys, I'm writing the simplest thing ever, just creating an ifstream to read in a text file and I have a weird error. Here is the code (note : the '<' missing for iostream and fstream are well written in my code but I couldn't write them here)
#include "genlib.h"
#include "simpio.h"
#include "random.h"
#include "vector.h"
#include "map.h"
#include <iostream>
#include <fstream>
int main() {
ifstream in;
in.open("Hamlet.txt");
if (in.fail()) Error("Could not open file");
return 0;
}
I get the following error after the ifstream in; line : "error : expected unqualified-id before '=' token"
Any idea what's going wrong ?
Thanks
The only thing unusual past ifstream in; is the Error call. My wild guess is that it's a poorly written macro. Try this instead:
int main() {
ifstream in;
in.open("Hamlet.txt");
if (in.fail()) { Error("Could not open file"); }
return 0;
}
Note the new braces around Error.
You need to add
using namespace std;
to use arbitrary names from the library without qualification. Otherwise, the declaration must be
std::ifstream in;
There is also the option
using std::ifstream;
but I wouldn't recommend it, since you probably won't be writing out std::ifstream all that often.
My guess is that in one of your own include files ("genlib.h" and "simpio.h" seem non-Standard), that you're #defined "in"
Try opening the file directly in the constructor:
ifstream inf ( "Hamlet.txt" , ifstream::in );
use std::ifstream
(and provide compilable code; those are not all standard headers, and what is Error()?)
Related
I am using the filetering_istream type to save the information in a decompressed file while using 'boost/iostreams/filtering_stream.hpp'. But I want to cast it into the ifstream type. It there any way to do it? Great thanks!
The code is as follows:
#include <istream>
#include <fstream>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/filter/gzip.hpp>
int main(){
std::ifstream file("test_data.dat.gz");
boost::iostreams::filtering_istream in;
in.push(boost::iostreams::gzip_decompressor());
in.push(file);
/* add code to convert filtering_istream 'in' into ifstream 'pfile' */
/* It seems that the following code returns a pointer NULL */
// std::ifstream* pfile = in.component<std::ifstream>(1);
return 0;
}
After trying boost::ref and boost::wrapper proposed by zett42, the ifstream really works. The only problem is that it doesn't give the phrases wanted.
In my text of .gz file, I wrote:
THIS IS A DATA FILE!
8 plus 8 is 16
But using the ifstream, I got:
is_open: 1
\213<\373Xtest_data.dat\361\360V"G\307G7OWE.\205\202\234\322b\205\314bC3.\327+>\314$
I am not sure what happened here, and can I do something to recover it?
From the reference of filtering_stream:
filtering_stream derives from std::basic_istream, std::basic_ostream
or std::basic_iostream, depending on its Mode parameter.
So no, you can't cast a filtering_stream directly to an ifstream because there is no inheritance relationship between the two.
What you can do instead, if your filter chain ends with a device that is an ifstream, you can grap that device by calling filtering_stream::component(). For streams this function returns a boost::iostreams::detail::mode_adapter (you can see the type by calling in.component_type(1)).
It's propably not a good idea to depend on an internal boost type (indicated by namespace "detail") which could change with next boost version, so one workaround is to use boost::reference_wrapper instead.
#include <iostream>
#include <istream>
#include <fstream>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/filter/gzip.hpp>
#include <boost/core/ref.hpp>
int main(){
std::ifstream file("test_data.dat.gz");
boost::iostreams::filtering_istream in;
in.push(boost::iostreams::gzip_decompressor());
in.push(boost::ref(file));
if( auto pfile = in.component<boost::reference_wrapper<std::ifstream>>( 1 ) )
{
std::ifstream& rfile = *pfile;
std::cout << "is_open: " << rfile.is_open() << "\n";
}
}
I am using boost to read a file
But when I set seekg to a position (~20000) in the file,
I get a runtime error
Microsoft C++ exception:
boost::exception_detail::clone_impl`<`boost::exception_detail::error_info_injector`<`std::ios_base::failure>>> at memory location 0x00EEC874.
Code:
ifstream if("file.bin",std::ios::binary)
if (if.is_open())
{
boost::iostreams::stream<boost::iostreams::mapped_file_source>is(fs);
is.seekg(20000, is.beg); //error is here
//// read
}
That code shouldn't compile. If it does, file a bug report with the compiler vendor.
if is a reserved keyword.
Assuming you messed up the code sample, (because you also had missing ;), it should just work but you may just have missing files/error handling:
Live On Coliru
#include <boost/iostreams/device/mapped_file.hpp>
#include <boost/iostreams/stream.hpp>
#include <fstream>
#include <iostream>
int main() {
std::ifstream ifs("main.cpp",std::ios::binary);
if (ifs.is_open())
{
boost::iostreams::stream<boost::iostreams::mapped_file_source> is("main.cpp");
if (is.seekg(200, is.beg))
std::cout << is.rdbuf();
}
}
When using ifstream class to read words from an input file, I have used the following expression:
#include <iostream>
#include <fstream>
int main(int argc, char *argv[])
{
std::ifstream inputStream(myFile.txt);
std::string myString;
myFile.open()
while(myFile.good())
{
myFile >> myString;
printf("%s \n", myString);
}
return 0;
}
The contents of myFile.txt are:
" This is a simple program. "
The compiles and executes as expected using g++ compiler.
However, the same code when compiled using msvc 2008, returns error at the extraction operator (>>) requiring me to replace the std::string with either an initialized character array or any of the supported native types.
This threw me off as I was expecting the usage of the standard library to be same across implementations.
I understand the compile error and know the way to fix it via using c_str().
But, it would help me a great deal, if someone could clarify why the usage for the standard library is different across platforms.
To me it is not starndard anymore !!
EDIT: Code updated to be complete. Content of myFile.txt updated.
Chances are that you forgot to #include <string>. Without it, Microsoft's version of <iostream> (and such) include enough of a declaration of std::string for some things to work, but other parts are missing, so you get strange, seemingly inexplicable failures.
One of the things that's missing is most of the operator overloads for std::string, which is exactly what you seem to be missing.
As an aside, while (myfile.good()) ... is pretty much a guaranteed bug -- you probably want:
while (myfile>>myString)
std::cout << myString << " \n";
Alternatively, you could do the job with a standard algorithm:
#include <string>
#include <algorithm>
#include <iterator>
#include <fstream>
#include <iostream>
int main() {
std::ifstream myfile("input.txt");
std::copy(std::istream_iterator<std::string>(myfile),
std::istream_iterator<std::string>(),
std::ostream_iterator<std::string>(std::cout, " \n"));
return 0;
}
The following compiles fine for me on MSVC 2010:
std::ifstream inputStream;
std::string myString;
inputStream.open("myFile.txt", std::ifstream::in);
while(inputStream.good())
{
inputStream >> myString;
}
Note: without using std::ifstream::in as my open mode, I got the same error as you. I suggest you check what value you have for this parameter.
I have really strange problem. In Visual C++ express, I have very simple code, just:
#include <fstream>
using namespace std;
int main()
{
fstream file;
file.open("test.txt");
file<<"Hello";
file.close();
}
This same code works OK in my one project, but when I create now project and use this same lines of code, no file test.txt is created. Please, what is wrong?ยจ
EDIT: I expect to see test.txt in VS2008/project_name/debug - just like the first functional project does.
Canonical code to write to a file:
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ofstream file;
file.open("test.txt");
if ( ! file.is_open() ) {
cerr << "open error\n";
}
if ( ! ( file << "Hello" ) ) {
cerr << "write error\n";
}
file.close();
}
Whenever you perform file I/O you must test every single operation, with the possible exception of closing a file, which it is not usually possible to recover from.
As for the file being created somewhere else - simply give it a weird name like mxyzptlk.txt and then search for it using Windows explorer.
Perhaps the executable is run in a different directory than it was before, making test.txt appear somewhere else. Try using an absolute path, such as "C:\\Users\\NoName\\Desktop\\test.txt" (The double backslashes are needed as escape characters in C strings).
fstream::open() takes two arguments: filename and mode. Since you are not providing the second, you may wish to check what the default argument in fstream is or provide ios_base::out yourself.
Furthermore, you may wish to check whether the file is open. It is possible that you do not have write permissions in the current working directory (where 'test.txt' will be written since you don't provide an absolute path). fstream provides the is_open() method as one way of checking this.
Lastly, think about indenting your code. While you only have a few lines there, code can soon become difficult to read without proper indentation. Sample code:
#include <fstream>
using namespace std;
int main()
{
fstream file;
file.open("test.txt", ios_base::out);
if (not file.is_open())
{
// Your error-handling code here
}
file << "Hello";
file.close();
}
You can use Process Monitor and filter on file access and your process to determine whether the open/write is succeeding and where on disk it's happening.
Theres two ways to fix this. Either do:
file.open("test.txt", ios::out)
#include <fstream>
using namespace std;
int main()
{
fstream file;
file.open("test.txt", ios::out);
file<<"Hello";
file.close();
}
Or you can create an ofstream instead of fstream.
#include <fstream>
using namespace std;
int main()
{
ofstream file;
file.open("test.txt");
file<<"Hello";
file.close();
}
I am getting an ofstream error in C++, here is my code
int main () {
ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a file.\n";
myfile.close();
return 0;
}
error from Dev-C++ 10
C:\devp\main.cpp aggregate
`std::ofstream OutStream' has
incomplete type and cannot be defined
Thanks in advance
You can try this:
#include <fstream>
int main () {
std::ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a file.\n";
myfile.close();
return 0;
}
The file streams are actually defined in <fstream>.
You may not be including the appropiate header file.
adding #include <fstream> at the beggining of your source file should fix the error.
Probably, you are including the wrong header file. There is a header <iosfwd> that is used for header files that need to reference types from the STL without needing a full declaration of the type. You still are required to include the proper header <iostream> in order to use the types in question.
Include fstream header file that's it. Because ofstream & ifstream are included in fstream.
Add #include <fstream>.
Code:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
std::ofstream myfile;
myfile.open("example.txt", std::ios::out);
myfile << "Writing this to a file\n";
myfile.close();
return 0;
}
I faced the same error because I forgot to use using namespace std;
after including it, the problem was solved.