5

Does open function have some sort of restriction as to what kind of string value is passed in?

ifstream file;
string filename = "output.txt";
file.open(filename);

I tried to pass a string value with a string variable, but when it tries to compile, the result is...

agent.cpp:2:20: error: ofstream: No such file or directory
agent.cpp: In function ‘std::string readingline(std::string)’:
agent.cpp:11: error: aggregate ‘std::ifstream file’ has incomplete type and cannot be     defined
agent.cpp: In function ‘int main()’:
agent.cpp:44: error: aggregate ‘std::ofstream writefile’ has incomplete type and cannot be defined

On the other hand, when I just pass a string value in quotes like "filename.txt" , it compile fine and runs fine.

ifstream file;
file.open("output.txt");

Why is this the case?

Is there a way to solve this problem?

Jason Kim
  • 18,102
  • 13
  • 66
  • 105
  • did you try to pass a pointer to a char array? – neeKo Dec 18 '11 at 03:52
  • 2
    See [Why does (i|o)fstream take a const char* parameter for a file name?](http://stackoverflow.com/questions/5972151/why-does-iofstream-take-a-const-char-parameter-for-a-file-name) – Seth Carnegie Dec 18 '11 at 03:58

3 Answers3

5

Sadly, this is how the constructor and open of std::(i|o)fstream are defined by the standard. Use file.open(filename.c_str()).

Some standard libraries provide an extension that allows std::string as a parameter, e.g. Visual Studio.

Xeo
  • 129,499
  • 52
  • 291
  • 397
  • Thank you Xeo. Using `file.open(filename.c_str())` worked out. – Jason Kim Dec 18 '11 at 04:07
  • 1
    It is not an extension anymore, but in compliance with the C++11 standard. – Bo Persson Dec 18 '11 at 10:13
  • @Bo: Wait, we got those in C++11? I must have missed that. *goes to skim through the standard* – Xeo Dec 18 '11 at 16:30
  • 1
    I suppose the reason why `const char*` was preferred over `std::string` is that filenames, by (POSIX) definition can never contain embedded nulls. Saying `file.open(fname.c_str())` makes that explicit to the programmer – sehe Dec 18 '11 at 19:06
1

I think your error messages may be unrelated to the code in question, but open takes a C-style const char* and not a C++ string. You'll need to use filename.c_str() in the call to make it work correctly.

Xeo
  • 129,499
  • 52
  • 291
  • 397
Mark B
  • 95,107
  • 10
  • 109
  • 188
1

I got the problem to go away by including fstream and passing filename.c_str() instead of just filename.

The message about an incomplete type is because you are missing a header (probably anyway, you didn't show a full example).

And open takes a c-style string, not the string class.

tpg2114
  • 14,112
  • 6
  • 42
  • 57