Click here to Skip to main content
15,891,372 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C++
#include "stdafx.h"
#include<iomanip>
#include <fstream>
#include<iostream>
using namespace std;
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
int main() {
    ifstream inFile;
    inFile.open("C:\\Users\Public\Documents\c++ test for overloading\alaki\test.data");
    if (!inFile) {
        cout << "Unable to open file";
        exit(1);
    inFile.close();
    return 0;
   }
}

How I can select the file and let my program show the things in it?
Posted

If you are doing it from the console, then you can use cin to get input.
You can use a loop of reading chunks and displaying it or adding it to a string to read the contents

#include <iomanip>
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main() {
    ifstream inFile;
    string file;
    cout << "Enter a file name:" << endl;
    cin >> file;
    //All \ need to be escaped with a 2nd \ like "C:\\Users\\Public\\Documents\\c++ test for overloading\\alaki\\test.data"
    inFile.open(file.c_str());
    if (!inFile.is_open()) { //you cant check the class for inequality... you need to call the is_open() method to see if it opened properley
        cout << "Unable to open file";
        //inFile.close(); //dont need to close... it never opened
        return -1; //you dont need exit and a return
    }
    char szContents[128]; //This can be any size you like. Dont make it too big (say more than 4096) unless you use new or malloc to create it.
    while (!inFile.eof()) {
        memset(szContents, 0, sizeof(szContents)); //empty the buffer
        inFile.read(szContents, sizeof(szContents) - 1); //include space for terminator
        cout << szContents;
    }
    inFile.close();
    return 0;
}
 
Share this answer
 
Comments
Olivier Levrey 4-Feb-11 8:28am    
My 5. I think this answers perfectly.
Not sure exactly what you're after, but as far as accessing files, note that all backslashes must be escaped in a string literal; you have escaped only the first backslash in
inFile.open("C:\\Users\Public\Documents\c++ test for overloading\alaki\test.data"); 
.
 
Share this answer
 
Comments
Olivier Levrey 4-Feb-11 8:17am    
good remark!
mf_arian 4-Feb-11 8:20am    
can you write in the way that you think is true , please?
Hans Dietrich 4-Feb-11 8:39am    
Every occurrence of '\' in a string literal must be doubled: '\\', like 'C:\\Users...".
mf_arian 4-Feb-11 8:52am    
I did it but it was not useful thanks

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900