2

I try to understand the file reading in c++ and try to read a file that doesn't exist deliberately

//includes ommited int main(int argc, char ** argv) { if(argc != 1) throw std::exception(); std::ifstream file(argv[0]); std::string content((std::istream_iterator<char>(file)), std::istream_iterator<char>()); std::cout << content.c_str() << std::endl; } 

DEMO

It prints the following:

ELF 

Why is it supposed to mean? Do I just get UB by doing this? Since I'm a Java coder I expected that some exception will be thrown if we try to read a file that doesn't exist...

1 Answer 1

5

argv[0] contains path to your executable.

http://www.gnu.org/software/libc/manual/html_node/Program-Arguments.html

The file name of the program being run is also included in the vector as the first element; the value of argc counts this element.

Just try to print it's contents:

std::cout << argv[0] << std::endl; 

You probably want to use argv[1].

"ELF" is the begin of file header of Executable and Linkable Format.

Sign up to request clarification or add additional context in comments.

3 Comments

Ok, now it just prints nothing
Maybe because of your condition to throw an exception. That should also be the behavior in the first case.
@St.Antario You should pass an argument to your executable - just append it after ./a.out on Coliru.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.