[英]Why does reading a file that doesn't exist print garbage characters?
I try to understand the file reading in c++
and try to read a file that doesn't exist deliberately 我试图理解用
c++
读取的文件,并试图故意读取不存在的文件
//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;
}
It prints the following: 它打印以下内容:
ELF
Why is it supposed to mean? 为什么要说呢? Do I just get UB by doing this?
这样我能得到UB吗? 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...
由于我是一名Java编码器,所以我希望如果我们尝试读取一个不存在的文件,将会抛出一些异常...
argv[0]
contains path to your executable. argv[0]
包含可执行文件的路径。
http://www.gnu.org/software/libc/manual/html_node/Program-Arguments.html
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.
argc的值计入此元素。
Just try to print it's contents: 只需尝试打印其内容:
std::cout << argv[0] << std::endl;
You probably want to use argv[1]
. 您可能要使用
argv[1]
。
"ELF" is the begin of file header of Executable and Linkable Format . “ ELF”是Executable and Linkable Format文件头的开头。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.