I tried to open a file in a non existing directory in C++ and for some reason my application didn't crash. I find that a bit "weird" because I'm used to C, where the equivalent program does crash. Here is my C++ version followed by the equivalent C version:
$ cat main.cpp
#include <fstream>
int main(int argc, char **argv)
{
std::ofstream f("/home/oren/NON_EXISTING_DIR/file.txt");
f << "lorem ipsum\n";
f.close();
printf("all good\n");
}
$ g++ main.cpp -o main
$ ./main
all good
When I try the equivalent thing with C I get a segfault:
$ cat main.c
#include <stdio.h>
int main(int argc, char **argv)
{
FILE *fl = fopen("/home/oren/NON_EXISTING_DIR/file.txt","w+t");
fprintf(fl,"lorem ipsum\n");
fclose(fl);
printf("all good\n");
}
$ gcc main.c -o main
$ ./main
Segmentation fault (core dumped)
Why is that?