C++ using fstream - c++

Ok so I haven't used C++ since highschool (used to work in borland C++)
Now I want to solve a problem in C++, yet I don't understand why fstream doesn't work
For some reason ios::in doesn't work.
#include <fstream>
fstream f("Cities.txt,ios::in);
How do I use Fstream properly?
Thanks in advance!
Note : I'm using Visual Studio 2008

change from
fstream f("Cities.txt,ios::in);
to
std::fstream f("Cities.txt" , std::ios::in);
^^^ ^ ^^^
namespace you miss" namespace
done!

What you have learned in your highschool probably was way before C++ was standardized in '97. As per the standard, all C++ library functions are part of the std namespace. In order to use fstream which is part of the standard namespace, you have to qualify it with std:: so, that makes your syntax as
#include <fstream>
std::fstream f("Cities.txt",std::ios::in);

As an alternative to std::fstream, consider std::ifstream (and std::ofstream):
#include <fstream>
…
std::ifstream f("Cities.txt");
std::ofstream o("output.txt");
std::string s;
while( f >> s )
o << s;
Personally, I find this more convenient than specifying the open mode.

You have to first create an object of ifstream class and then open the file.
Do it this way.
#include <fstream>
std :: ifstream f ("Cities.txt",ios::in) ;
Then check whether it is open and start working with it.
You are also missing the " after file name.

You can also write
#include <fstream>
using namespace std;
fstream f("Cities.txt",ios::in);
The using directive allows you to not write std:: before everything. Beware, it might be bad practice, but in small programs it should not be an issue.

Related

Strings as File names

If I set a string as a filename, it doesn't work and I have no idea why. (I'm using codeblocks and it seems to work on other IDEs)
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
string FileName="Test.txt";
ofstream File;
File.open(FileName);
}
This does not work,while this next one does:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ofstream File;
File.open("Test.txt");
}
Error message:
no matching function for call to std::basic_ofstream::open(std::string&)
Can someone help a bit with this problem, I cannot understand why this error occurs.
Due to what should be considered a historical accident in the early era of C++ standardisation, C++ file streams originally didn't support std::string for filename parameters, only char pointers.
That's why something like File.open(FileName), with FileName being a std::string, didn't work and had to written as File.open(FileName.c_str()).
File.open("Test.txt") always worked because of the usual array conversion rules which allow the "Test.txt" array to be treated like a pointer to its first element.
C++11 fixed the File.open(FileName) problem by adding std::string overloads.
If your compiler doesn't support C++11, then perhaps you should get a newer one. Or perhaps it does support C++11 and you just have to turn on the support with a flag like -std=c++11.

C++ - Fstream not generating a new line

I have searched through a lot of questions on this website which are pretty much the same, but nothing works for me. In the first place, let me tell you that I am using Code::Blocks and I am using Ubuntu. This is my code:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream file("code.out");
string write;
getline(cin, write);
file << write << "\n";
file.close();
}
Tried \n, tried \r\n (\r doesn't seem to do anything for me really). Oh and by the way, if you could also make it work with word-by-word reading that would be great. Thank you very much!
EDIT: Hey guys, I solved it. Thanks for the answers tho! I needed to add a ios::app after code.out!
Should you be using ofstream. http://www.cplusplus.com/reference/fstream/ofstream/
Then check that it has opened.
Then check you have read some data - debugger is handy for that
EDIT
You need
ofstream file("code.out", ios::out | ios::app)
Try this code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
fstream file("code.out", std::fstream::out);
string write;
getline(cin, write);
file << write << '\n';
file.close();
}
Explicitly passing the std::fstream::out through the constructor got it to behave correctly for me and produced the newline.
Edit:
Note for future reference, my solution produces the newline but this will overwrite data currently found in the file. Ed Heal has code for appending to a file in his answer.
Adding
std::fstream::app
to my code would then mimic Ed Helms solution. Please mark his answer if appending functionality is actually what you needed. This answer will be for others who have a similar newline issue who want to overwrite the file.
I also had that problem once.
Try using ofstream instead of fstream. Maby that'll help, because I used that too.

Writing To a file using fstream will erase the file

I have a problem, I have a saved text file, I want to use fstream header file in C++ to write something to that file, but using ofstream will erase the whole file as soon as I run the compiled application, why and how to avoid it?
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
ofstream write("1.txt");
return 0;
}
You need to tell ofstream to append to the file.
std::ofstream write("1.txt",std::ios::app);
There are several other flags that control similar characteristics of the stream, read a book or reference for more information.

Very basic C++ error

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()?)

mixing C and C++ file operations

I am writing a file splitting program, to assist with using large files with iPod notes. I want to use tmpfile() in cstdio but it returns a file* not an fstream object. I know it's not possible in standard C++ but does anyone know any libraries that work well with the standard that have the ability to convert a FILE* to an std::fstream object? Or, if not is tmpfile() functionality available in the standard, or another library?
Thanks!
My OS is Windows XP and I use either Dev-C++ 4.9.9.2 or MS Visual Studio 2008 as my compiler.
If all you want is a temporary file, use tmpnam() instead. That returns char* name that can be used for a temporary file, so just open a fstream object with that name.
Something like:
#include <cstdio>
#include <fstream>
...
char name[L_tmpnam];
tmpnam(name);
//also could be:
//char *name;
//name = tmpnam(NULL);
std::fstream file(name);
You do have to delete the file yourself, though, using remove() or some other method.
You can use the benefits of c++ streams by pumping your data via the << syntax into a std::stringstream
and later write it the .str().c_str() you get from it via the the C-API to the FILE*.
#include <sstream>
#include <cstdio>
#include <string>
using namespace std;
int main()
{
stringstream ss;
ss << "log start" << endl;
// ... more logging
FILE* f_log = fopen("bar.log", "w");
string logStr = ss.str();
fwrite(logStr.c_str(), sizeof(char), logStr.size(), f_log);
fclose(f_log);
return 0;
}
Even if you manage to convert a FILE* to an std::fstream, that won't work as advertised. The FILE object returned by tmpfile() has a special property that, when close()'d (or when the program terminates), the file is automatically removed from the filesystem. I don't know how to replicate the same behavior with std::fstream.
You could use tmpnam mktmp to obtain a temporary file name, open it with a stream and then delete it with remove.
char *name;
ifstream stream;
name = mktmp("filename");
stream.open(name);
//do stuff with stream here.
remove(name);//delete file.
Instead of using std::fstream, you could write a simple wrapper class around FILE*, which closes it on destruction. Should be quite easy. Define operators like << as necessary.
Be sure to disallow copying, to avoid multiple close() calls.
g++ has __gnu_cxx::stdio_filebuf and __gnu_cxx::stdio_sync_filebuf, in ext/stdio_filebuf.h and ext/stdio_sync_filebuf.h. It should be straight-forward to extract them from libstdc++ if your compiler is not g++.