| CodeGuru Home | VC++ / MFC / C++ | .NET / C# | Visual Basic | Newsletters | VB Forums | Developer.com |
|
|||||||
| C++ (Non Visual C++ Issues) Ask or answer C and C++ questions not related to Visual C++. This includes Console programming, Linux programming, or general ANSI C++. |
![]() |
|
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
#1
|
|||
|
|||
|
C++ File handling VS C file Handling query
If the fclose is not used in case of C, file remains open in the memory. In case of C++, fclose is called automatically and there is no memory leak.
Are there any plus/minus points of C++ file handling library (ifstream,ofstream) over C file handling library? Pl explain with example if possible. |
|
#2
|
|||
|
|||
|
Re: C++ File handling VS C file Handling query
Quote:
Quote:
Quote:
Regards, Paul McKenzie |
|
#3
|
|||
|
|||
|
Re: C++ File handling VS C file Handling query
Try this:
Code:
struct FileOpen{
FileOpen(FILE &* f, const char * name, const char * mode){
f = fopen(name, mode);
fp = f;
}
~FileOpen(void){
if (fp) fclose(fp);
}
FILE * fp;
};
FILE * myfile;
FileOpen fo(myfile, "c:\\test.txt", "w");
if (!myfile) return;
|
|
#4
|
|||
|
|||
|
Re: C++ File handling VS C file Handling query
There are two primary advantages to streams over the printf family of functions:
1) Type safety 2) Polymorphism By the first, I mean that it's impossible to have the types of errors you could get with printf, where you try to output a double using %d, and get garbage. By the second, I mean that a FILE* is a FILE*, and you can't use it for much else. With streams, an ofstream is also an ostream, and you can define your own objects which are also ostreams, and all of your IO code can be written to ostreams and istreams with no regard to where the data is actually *going*. Now, there are some advantages to the printf family over streams, as well: 1) Marginally faster in some cases (usually not a concern; IO is notoriously slow anyway) 2) More compact syntax can make the intended operation clearer 3) scanf() is capable of trying to match specific characters, which is a capability that istreams don't have (you'd need a regex package). |
|
#5
|
|||
|
|||
|
Re: C++ File handling VS C file Handling query
Quote:
__________________
C + C++ Compiler: MinGW port of GCC Build + Version Control System: SCons + Bazaar Look up a C/C++ Reference and learn How To Ask Questions The Smart Way Kindly rate my posts if you found them useful
|
![]() |
| Bookmarks |
|
||||||
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|