2016-11-22 5 views
-1

Ich möchte den folgenden Code bearbeiten, um mehrere andere Dateien im proc-Verzeichnis zu lesen und zu lesen. Darf ich eine Anleitung zur Verbesserung dieses Codes erhalten, um andere proc-Dateien als nur die Betriebszeit zu betrachten? Vielen Dank.Lesen mehrerer Dateien mit C++

#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 
} 
+6

Setzen Sie Ihren Lesecode mit einer Funktion geschrieben. Erhalten Sie alle Ihre Dateinamen in einem Vektor. Iteriere über den Vektor, der deine Funktion für jeden Dateinamen aufruft. – drescherjm

+0

Sie könnten versuchen, den Dateinamen '"/proc/uptime "' in den Namen der anderen Dateien zu ändern, die Sie lesen möchten? – Galik

Antwort

1

Hier wird es stattdessen in einer Funktion

#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; 
} 
+0

Danke Benutzer 2220115. Das hat geholfen. – martinbshp

Verwandte Themen