C file I/O vs <fstream>

Pages: 12
vrakas wrote:
you mean that doing cout<<'\n'; instead of cout<<endl; makes your program faster?

I'd say it makes your program more rational. Much of popularity of endl comes from early erroneous textbooks that called endl "portable end of line", with '\n' being somehow "not portable", and many people took that as truth.

Stroustup uses \n by default: http://www2.research.att.com/~bs/3rd_code.html
Last edited on
Prefer C++ approaches, they are safer. Exhibit A:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <cstdlib>
#include <iostream>
#include <ctime>
#include <cstdio>
#include <fstream>

using namespace std;

#define time double(clock())/CLOCKS_PER_SEC

int main()
{
    {
    double a=time;
    ofstream fout;
    fout.open("bla1.txt", ios::out);
    for (int i=1; i<=100000; i++) fout<<"Hello World No. "<<i<<endl;
    cout<<time-a<<endl;
    }
    {
    double a=time;
    FILE* fout;
    fout=fopen("bla2.txt", "w");
    for (int i=1; i<=100000; i++) fprintf(fout, "Hello World No. %i\n", i);
    fclose(fout); // <-- don't forget about me
    cout<<time-a<<endl;
    }
    system ("pause");
}


Last edited on
¿What if you already have a FILE* ? By instance, you've got it through popen()
Also, as you can't return an stream from a function *, you lose RAII

*they don't have a copy constructor.
(prev c++0b with its move constructor/assignment operator)
Last edited on
Also, as you can't return an stream from a function

3 words for you: return by reference.
@viliml
That doesn't work if the stream was created inside the function.
Last edited on
unique_ptr
@Peter87: Why would you create a stream inside the function? You already have all the streams defined, and even if you don't know what stream to use, you can do this:
1
2
3
4
5
6
7
8
9
10
11
12
13
/* yadda yadda yadda, declare function name...
then when it comes to returning, */
switch (typeid(/*the type of the stream to return*/))
{
      case typeid(ostream):
      /*the type of the stream to return*/& stm=cout;
      case typeid(ofstream):
      /*you know what*/&& shm=ofstream();
      case typeid(istringstream):
      /*uhhh*/&& stm=istringstream();
      }
return stm;
}
Last edited on
Because ofstream bar = foo(args); looks better than
1
2
ofstream bar;
foo(bar, args);


You shouldn't return a reference to a local variable.
Topic archived. No new replies allowed.
Pages: 12