L.Acmery
L.Acmery

Reputation: 25

Why I can not use seekg(0, ifstream::end) when I open a linux system file as ifstream

I want using C++ to get the machine's CPU information, and my code is:

    ifstream cpu_info_file("/proc/cpuinfo", ifstream::in|ifstream::binary);
    streampos sp = cpu_info_file.tellg();
    cout << sp << endl;

    cpu_info_file.seekg(0, ifstream::end);
    sp = cpu_info_file.tellg();
    cout << sp << endl;

    cpu_info_file.seekg(-10, ifstream::cur);
    sp = cpu_info_file.tellg();
    cout << sp << endl;

    cpu_info_file.seekg(0, ifstream::beg);
    sp = cpu_info_file.tellg();
    cout << sp << endl;


but I got the output:

0
-1
-1
-1

after that I copy /proc/cpuinfo to my project path, and modify the code:

ifstream cpu_info_file("cpuinfo",ifstream::in|ifstream::binary);

and I got the right output:

0
10424
10414
0

I spent a whole day trying to figure out the reason, but if I open any file under /proc and use file.seekg(n, ifstream::end), the return of file.tellg() will always be -1 and I can not move the streampos anymore.

So why I can not read the file under /proc as the file under my project directory?

Upvotes: 1

Views: 202

Answers (0)

Related Questions