This question came up on the Yahoo c-prog group.
In C, if you open a binary file for reading and appending, the file is created if it doesn't exist. (See man fopen.)
In C++, if you open a binary file for reading and appending, the file is not created if it doesn't exist.
Here's the C code, which attempts to open the file GROUP1.DAT:
#include <stdio.h>
int main()
{
FILE *pMyFile;
pMyFile = fopen( "GROUP1.DAT", "a+b" );
if ( NULL == pMyFile )
{
fprintf( stderr, "Can't open file." );
}
fprintf( pMyFile, "%s\n", "Data line 1" );
fclose( pMyFile );
return 0;
}
Here's the C++ code, which attempts to open the file GROUP2.DAT:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream myFile;
myFile.open( "GROUP2.DAT",
ios::in | ios::out | ios::binary | ios::app );
if ( ! myFile )
{
cerr << "Can't open file";
return 1;
}
myFile << "Data line 1\n";
myFile.close();
return 0;
}
Here's the output:
$ rm *.DAT $ gcc -Wall fileTest1.c -o fileTest1 $ ./fileTest1 $ ls *.DAT GROUP1.DAT $ g++ -Wall fileTest2.cpp -o fileTest2 $ ./fileTest2 Can't open file. $ ls *.DAT GROUP1.DAT $