为什么读取不存在的文件会打印垃圾字符?

时间:2015-11-15 07:38:21

标签: c++ file

我尝试理解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;
}

DEMO

它打印以下内容:

ELF

为什么这意味着什么?这样做我只是得到UB吗?由于我是一个Java编码器,我预计如果我们尝试读取一个不存在的文件,就会抛出一些异常......

1 个答案:

答案 0 :(得分:5)

argv[0]包含可执行文件的路径。

  

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

     

正在运行的程序的文件名也包含在向量中作为第一个元素; argc的值计算此元素。

试着打印它的内容:

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

您可能想要使用argv[1]

“ELF”是Executable and Linkable Format的文件头的开头。