Howdy, Stranger!

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

Categories

Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

I/O data from a folder

KassamKassam Posts: 26Member
Hi,

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 ?

Thanks.

Comments

  • furnymanfurnyman Posts: 2Member
    #include
    #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
    fin.open(argv[1]);
    if(fin.bad()){
    //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.
  • furnymanfurnyman Posts: 2Member
    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.