Thread: Reading .dat files from a folder in current directory...

  1. #1
    Registered User
    Join Date
    Apr 2009
    Location
    ...creepy
    Posts
    75

    Reading .dat files from a folder in current directory...

    So, I just recently deleted my previous post from last night and I've been working with it to consolidate and try to touch up my screw-ups...boo...

    Anywho, I am basically trying to read in values from .dat files from a folder that is in the current directory of the program. I am running Linux if that matters...

    So, kind instructions to those who are willing to help:

    1.) make a new directory in your home folder "FOLDER", make a folder named "DATA" inside "FOLDER", and then make up two .dat files with whatever integers you want, and however many integers you want.
    2.) Next, copy and paste this .cpp code into "FOLDER" and try compiling/running.

    The instructions I have told you are exactly where my .dat files are and my .cpp code. When I run the program, I get this error:

    Enter directory with files available for use: InputFiles/
    Error(2) opening InputFiles/
    What is wrong with it? I don't understand...

    Here is my code, and I apologize sincerely for the long post. If you see any errors (which I'm sure there will be plenty!!), do not be bashful. Let me know! Oh, and my CalcMax() function isn't complete FYI, but I can do that on my own time. If you are using Windows/Mac, please change the instructions as necessary...Thank you in advance for all the help!!! Let me know ASAP please!

    Code:
    #include <sys/types.h>
    #include <dirent.h>
    #include <errno.h>
    #include <vector>
    #include <string>
    #include <iostream>
    #include <fstream>
    #include <cstdlib>
    #include <cstring>
    
    using namespace std;
    typedef vector<string> stringVector;  //Defines a vector of string values
    const int MAX_SIZE = 31;
    
    void OpenInputFile(ifstream&, string);
    void OpenOutputFile(ofstream&, string);
    int ReadArray(ifstream&, int[]);
    float CalcAverage(int[], int array_size);
    float CalcMax(int array[], int array_size);
    int getDir(string dir, stringVector &files);
    
    int main()
    {
        ifstream indiv_file;
        ofstream ofs_max;
        ofstream ofs_average;
        int array[MAX_SIZE], next, count = 0;
        float average_temp, maximum_temp;
        int array_size;
        string dir, out_file_max = "MaxsOfArrays.txt", out_file_average = "AvgsOfArrays.txt";
       
        cout << "Enter directory with files available for use: ";  //Lists the files in the current directory you could input .
        cin >> dir;
        stringVector files = stringVector();
        OpenOutputFile (ofs_max, out_file_max);
        OpenOutputFile (ofs_average, out_file_average);
        
        getDir (dir, files);
       
        int fsize = files.size();
        for (unsigned int i = 0; i < fsize; i++)
        {
            count = 0;
           
            if (files[i].at(0)!= '.') // if the file is a valid file
            {
                cout << endl << dir + files[i] << endl;
                indiv_file.open((dir + files[i]).c_str());
               /*if (indiv_file.fail())
               {
                  cout << "Fail";
                  return 0;
               }*/
               
    	   OpenInputFile (indiv_file, (dir+files[i]));
               array_size = ReadArray(indiv_file, array);
               average_temp = CalcAverage(array, array_size);
               //maximum_temp = CalcMax(array, array_size);
             
               while (indiv_file >> array[count])
               {
                     cout << array[count];
                     count++;
                     if(count == MAX_SIZE)
                         break;
               }
               for (int j = 0; j < array_size; j++)
                   {
                   cout << array[j] << " ";
               }
              
            }
            indiv_file.close();
         }
        return 0;
    }
    //--------------------------------
    int getDir (string dir, stringVector &files)
    {
            DIR *dp;
            struct dirent *dirp;
           
            if((dp  = opendir(dir.c_str())) == NULL) {
                    cout << "Error(" << errno << ") opening " << dir << endl;
                    return errno;
            }
            while ((dirp = readdir(dp)) != NULL)  {
                    files.push_back(string(dirp->d_name));
            }
            closedir(dp);
            return 0;
    }
    //---------------------------------------
    void OpenInputFile(ifstream &in_file, string file_name)
    {
         in_file.open(file_name.c_str());
         if (in_file.fail())
         {
            cout << "Failed to open file." << endl;
            exit(1);
         }
    }

  2. #2
    Registered User
    Join Date
    Mar 2009
    Posts
    14
    In cases like this, it's a good idea to try to isolate the problem. Comment out everything that's not related to opening the file. Hardcode the file name in the call to open().

    I played around with the code, and believe your problem stems from the fact that you're trying to open indiv_file twice, and that you're closing it even when it hasn't been opened.

  3. #3
    Registered User
    Join Date
    Apr 2009
    Location
    ...creepy
    Posts
    75
    by the time indiv_file.close() comes in the code, I definately have opened it by that point in the code. what would the problem be by opening it twice if it was already open?!?

  4. #4
    Registered User
    Join Date
    Mar 2009
    Posts
    14
    Basic question, but are you sure your DATA folder is named InputFiles? Your post indicates that you're stopping in getDir(). With errno=2, strerror(errno) gives "No such file or directory." Using your code, unchanged except for commenting out references to OpenOutputFile(), ReadArray() and CalcAverage(), I get past getDir() as long as I enter the correct name of the DATA folder. There may be funny things going on with slashes and backslashes, so experiment.

    Other errors:
    When I swap the call to close() with the line above it, thus moving close() inside the if statement, then the first call to open() succeeds. The second call to open(), inside OpenInputFile(), fails, probably because the file is already open.


    I'd recommend starting over; write a few lines of code and then test them by compiling and running. Use a lot of output statements so you know the program is producing the values that you expect it to. Testing a few lines at a time is much easier than a whole program at once.

    Caveat: I'm using Windows, but I wouldn't think that makes a difference.

  5. #5
    Registered User
    Join Date
    Apr 2009
    Location
    ...creepy
    Posts
    75
    so how should my code look iusing what you said in your last post DirkMaas?

  6. #6
    Registered User
    Join Date
    Apr 2009
    Location
    ...creepy
    Posts
    75
    never mind, stupid question!!! my b, but do you have any tips for rounding numbers that I get back from my average function?

  7. #7
    Registered User
    Join Date
    Apr 2009
    Location
    ...creepy
    Posts
    75
    and what line of code or cstring member function should I use to make my "February.dat" file turn into "February" for my output,

    i.e.
    Code:
    cout << "The average temperature in" << shortened_month << "was :  " << average_temp;

  8. #8
    Registered User
    Join Date
    Mar 2009
    Posts
    14
    For rounding, do an internet search for "C++ round number." You'll get a bunch of hits. There's some code here: CIS Department > Tutorials > Software Design Using C++ > Arithmetic and Formatting of Output in C++. For pulling a substring out of a string, I'd use a combination of find() and substr(). Reference here: C++ Strings [C++ Reference].

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 20
    Last Post: 02-23-2010, 01:49 AM
  2. How can i check a directory for certain files?
    By patrioticpar883 in forum C++ Programming
    Replies: 13
    Last Post: 02-01-2008, 05:27 PM
  3. I Need To Know Some Things That I Can Put Into A Batch File
    By TheRealNapster in forum A Brief History of Cprogramming.com
    Replies: 1
    Last Post: 10-20-2003, 08:12 PM
  4. Reading files in a directory
    By roktsyntst in forum Windows Programming
    Replies: 5
    Last Post: 02-07-2003, 10:04 AM
  5. Replies: 0
    Last Post: 07-12-2002, 01:40 PM