martinbshp martinbshp - 13 days ago 8
C++ Question

Read multiple files with C++

I would like to edit the below code to look at and read several other files in the proc directory. May I get some guidance on how to improve this code to look at other proc files other than just the uptime. Thank you.

#include <fstream>
#include <iostream>
#include <string>
#include <cstdlib> // for exit()

int main()
{
using namespace std;

// ifstream is used for reading files
// We'll read from a file called Sample.dat
ifstream inf("/proc/uptime");

// If we couldn't open the input file stream for reading
if (!inf)
{
// Print an error and exit
cerr << "Uh oh, file could not be opened for reading!" << endl;
exit(1);
}

// While there's still stuff left to read
while (inf)
{
// read stuff from the file into a string and print it
std::string strInput;
getline(inf, strInput);
cout << strInput << endl;
}


return 0;

// When inf goes out of scope, the ifstream
// destructor will close the file
}

Answer

Here it is written with a function instead

#include <fstream>
#include <iostream>
#include <string>
#include <cstdlib> // for exit()

using namespace std;

void readfile(string file)
{

   ifstream inf (file.c_str());

    if (!inf)
    {
        // Print an error and exit
        cerr << "Uh oh, file could not be opened for reading!" << endl;
        exit(1);
    }

    while (inf)
    {
        std::string strInput;
        getline(inf, strInput);
        cout << strInput << endl;
    }
}

int main()
{
    cout << "-------------------obtaining Totaltime and Idletime----------------" << endl;
    readfile("/proc/uptime");

    return 0;
}
Comments