I am using C ++ fstream to read the configuration file.
#include <fstream> std::ifstream my_file(my_filename);
Right now, if I pass the directory path, it silently ignores this. For example. my_file.good() returns true even if my_filename is a directory. Since this is an unintentional input for my program, I like to check it and throw an exception.
How to verify that a fstream just opened is a regular file, directory, or stream?
I can't seem to find a way:
- get the file descriptor from the given ifstream.
- use another mechanism to find this information in ifstream.
In the discussion of the forum, it was suggested that this is impossible because it depends on the OS and therefore can never be part of the standard C ++ standard.
The only alternative I can think of is to rewrite my code to completely get rid of ifstream and resort to the file descriptor C method ( *fp ), as well as fstat() :
#include <stdio.h> #include <sys/stat.h> FILE *fp = fopen(my_filename.c_str(), "r"); // skip code to check if fp is not NULL, and if fstat() returns != -1 struct stat fileInfo; fstat(fileno(fp), &fileInfo); if (!S_ISREG(fileInfo.st_mode)) { fclose(fp); throw std::invalid_argument(std::string("Not a regular file ") + my_filename); }
I prefer fstream. Hence my question.
c ++ c ++ 11 fstream ifstream
Macfreek
source share