Reading from .in file and giving output to .out file

I have created a program that gives result when it receives input from keyboard, which is very old way I know. So I want to know how to open .in Files using freopen() and output result to .out file. I know ifstream and ofstream, gets(), puts() etc., but I want to know how to manage files using "FILE" class. A link to my question, if answered anywhere, would also be very much appreciated. Cause Google ain't cooperating with me. If you think I'm stupid to ask this here, a little help will be appreciated.
Last edited on
You're mixing up a whole heap of different ways of doing files.

If you're using C++, I'd highly recommend using std::fstream. It's isn't hard, either: once you've opened the file, you can use it exactly the same way as std::cout:
1
2
3
4
5
6
7
8
9
10
11
12
#include <fstream>

int main() {
    std::ifstream in("file.in");
    double d;
    in >> d;
    
    std::ofstream out("file.out");
    out << d * 2 << std::endl;

    return 0; // `in' and `out' are automatically closed here
}


On the other hand, the FILE* ADT is a C construct, which is why you're not finding it if you're looking at C++ sites. I won't go into it here (because I don't think it's a good option, for a bunch of reasons), but a quick search found this: https://www.cs.bu.edu/teaching/c/file-io/intro/

Note that, as you can see here, you'll have to use the c-style fprintf and so on if you want to read/write to them.
Last edited on
The FILE and related functions are C-languages way of handling files. The C++'s I/O-streams are more versatile and generic. Are you sure that you want to learn C rather than C++?


Almost all environments do support input/output redirection. Rather than executing program and then typing input:
foo

you can redirect input from a file:
foo < inputfile > outputfile


Therefore, "gives result when it receives input from keyboard" is not old way; it is very current way for we can replace the "from keyboard" with a "from a file or another program" outside of the program.
Topic archived. No new replies allowed.