Adeeb Adeeb - 1 month ago 5
C++ Question

How do file operations work in C++ since they are different from Java?

I'm a Java developer, so when trying to operate on a file you instantiate an object of the class, File. The object, by default, will have methods such as

getAbsoluteFile()
.

In C++, however, according to this, you use a type called FILE which is defined within the stdio.h header file. Since it is not an object but a type, it will not have methods so how does one operate on it -- in particular, how does one rename a FILE?

What is the equivalent of having an object which has methods in C++ if it's different from Java (it seems different, judging from the File scenario)?

Answer

FILE is from the C standard library and is included in C++ for backwards compatibility. C doesn't provide support for OOP so it doesn't have methods at all. You operate on FILEs with free functions instead.

If you look at the sidebar on the site you linked you'll see a list of functions from the cstdio header. Most of the functions that have names starting with f take a FILE* as the first parameter. To rename files you can use rename; it doesn't take a FILE*, it takes two paths (as char*).

The more C++ way of doing file I/O is to use streams instead.

Comments