I/O data from a folder


Assume I have a folder that contains few files with txt extension, in case I need to get the data ( usually characters ) stored in these files and put them, for instance, in a string of characters, what would be the apprpriate code ?



  • #include
    using namespace std;

    int main(int argc, char* argv[])
    //Open a text file in current directory and echo it's contents
    //to cout
    ifstream fin;
    char c;

    if(argc != 2) return 1; //wrong number of args
    //file didn't open properly
    cout << argv[1] << " failed to open." << endl;
    return 1;

    //Read in a char, print it to cout
    while(!fin.eof()) {
    fin >> c;
    if(fin.fail() && !fin.eof()) {
    cout << endl << "Read error" << endl;
    return 1;
    cout << c;

    return 0;

    pass a filename to the program and it will be opened an printed to stdout.

    fin is an input file stream. You treat is just like an iostream.

    The code currently doesn't recognise end of lines, but that would be easy to fix.
  • btw, it's good practice to do a fin.close() once you have finished reading from the file.

    ps. I just realized you didn't specify a language in your question. I guess i read the question i wanted to read. The example code is c++.

    If you wanted c code i can do that too.
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!


In this Discussion