Skip to content

Instantly share code, notes, and snippets.

@macfreek
Last active August 29, 2015 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save macfreek/5bfab1be77784cc048d7 to your computer and use it in GitHub Desktop.
Save macfreek/5bfab1be77784cc048d7 to your computer and use it in GitHub Desktop.
Test C++ open() of a file or directory
// Test how open() or ifstream() behave when reading a directory, file or stream.
// Written 2015 by Freek Dijkstra
// Contributed to public domain
// See http://stackoverflow.com/questions/29310166/check-if-a-fstream-is-either-a-file-or-directory
#include <iostream>
#include <fstream>
#include <cerrno>
#include <cstring>
int main(int argc, char *argv[]) {
for (int i = 1; i < argc; i++) {
std::ifstream my_file;
try {
// Ensure that my_file throws an exception if the fail or bad bit is set.
my_file.exceptions(std::ios::failbit | std::ios::badbit);
std::cout << "Read file '" << argv[i] << "'" << std::endl;
my_file.open(argv[i]);
} catch (std::ios_base::failure& err) {
std::cerr << " Exception during open(): " << argv[i] << ": " << strerror(errno) << std::endl;
continue;
}
try {
std::string line;
while (std::getline(my_file, line))
{
std::cout << " read line: " << line << std::endl;
}
} catch (std::ios_base::failure& err) {
if (errno == 0) continue; // exception is raised due to EOF, no real error.
std::cerr << " Exception during read(): " << argv[i] << ": " << strerror(errno) << std::endl;
}
}
}
/*
Compiled with:
g++ -Wall -g -std=c++11 -o test test.cc
Make test environment:
mkdir testdir
echo "hello world" > testdir/file_with_trailing_lf
echo -n "hello world" > testdir/file_without_lf
Testing:
uname -srm; ./test testdir/file_without_lf testdir/file_with_trailing_lf testdir no_such_file
Results:
Darwin 14.1.0 x86_64
Read file 'testdir/file_without_lf'
read line: hello world
Read file 'testdir/file_with_trailing_lf'
read line: hello world
Read file 'testdir'
Exception during read(): testdir: Is a directory
Read file 'no_such_file'
Exception during open(): no_such_file: No such file or directory
Linux 2.6.32-042stab092.3 i686
Read file 'testdir/file_without_lf'
read line: hello world
Read file 'testdir/file_with_trailing_lf'
read line: hello world
Read file 'testdir'
Exception during read(): testdir: Is a directory
Read file 'no_such_file'
Exception during open(): no_such_file: No such file or directory
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment