Thread: I/O Problems - fstream

  1. #1
    Registered User mol's Avatar
    Join Date
    Oct 2001
    Posts
    19

    I/O Problems - fstream

    Ok. Be a little gentle. Im coming from microprocessor background so file i/o is a bit new to me. Anyway, here is some code below. Its pretty simple, its reading a file that has multiple lines of ints in it. It writes all the ints to the output file on one line. Then it is SUPPOSED to read the file again, this time computing the average and outputting it on the next line.

    But, in the debugger I get a divide by 0 error...so something is wrong with the i/o operation. *sigh*

    Can anyone lend a hand?

    PHP Code:

    #include <iostream>
    #include <iomanip>
    #include <fstream>

    using namespace std;

    void main()
    {
        
    int count;
        
    int num;
        
    int total;
        
    int avg;

        
    ifstream inData;
        
    ofstream outData;

        
    // lets get them all on one line
        
    inData.open("datfile1.txt");
        
    outData.open("outdata.txt");

        while(
    inData >> num)
        {
            
    outData << num << " ";
        }

        
    outData << endl;

        
    inData.close();

        
    // lets get the avg of all ints in the file
        
        
    inData.open("datfile1.txt");

        
    count 0;
        
    avg 0;

        while(
    inData >> num)
        {
            
    total += num;
            
    count++;
        }
        
        
    avg total/count;
        
    outData << avg << endl;

        
    inData.close();

    mol
    aka version2

    life is just 1's and 0's

  2. #2
    Registered User
    Join Date
    Aug 2001
    Posts
    155
    look at outdata.txt to make sure it data got written correctly. You can comment out everything after closing inData and before reopening it to try to get it to run to this point first, because what you have looks like it should work. If it writes to outdata.txt ok then display just total and count after reading them in and not do the avg calculation. Those steps should help you localize the problem.

  3. #3
    Registered User mol's Avatar
    Join Date
    Oct 2001
    Posts
    19
    Ok. I have been playing a bit with it and I have found that the problem must lie in how I am opening and closing the file. Reason: if I take the first routine out and only open the file one time then the second routine works. So, now my question is...

    Am I doing this the right? Is there a better way to re-read a file that doesnt involve sticking all of the contents in ram? Am I performing the open and close correctly?
    mol
    aka version2

    life is just 1's and 0's

  4. #4
    the hat of redundancy hat nvoigt's Avatar
    Join Date
    Aug 2001
    Location
    Hannover, Germany
    Posts
    3,130
    Look at this alternative method. You can do it all in one loop if
    you like. You should check if you really opened the files
    though. Also, main returns int. Always. And you might try
    to close your outputfile after writing to it ;-)

    PHP Code:
    #include <iostream>
    #include <fstream>

    using namespace std;

    int main()
    {
        
    int count 0;
        
    int num 0;
        
    int total 0;
        
    int avg 0;

        
    ifstream inData;
        
    ofstream outData;

        
    inData.open("datfile1.txt");
        
    outData.open("outdata.txt");

        
    // check if the open calls actually succeeded !!!

        
    while(inData >> num)
        {
            
    outData << num << " ";

            
    total += num;
            
    count++;
        }

        
    avg total/count;

        
    outData << endl << avg << endl;

        
    inData.close();
        
    outData.close();

        return 
    0;

    hth
    -nv

    She was so Blonde, she spent 20 minutes looking at the orange juice can because it said "Concentrate."

    When in doubt, read the FAQ.
    Then ask a smart question.

  5. #5
    Registered User mol's Avatar
    Join Date
    Oct 2001
    Posts
    19
    Thats how I would do it as well, but for this one I have to make each read independent. I am still trying to figure it out. It is rather maddening.

    Oh, and just so everyone knows. I have initialized all the variables, so that is not the problem I am having.
    mol
    aka version2

    life is just 1's and 0's

  6. #6
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    I ran your code and it works fine except that "total" needs to be initialized. Either:

    int total = 0;

    or before the loop.

  7. #7
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    I believe your problem may be it can't find datfile1.txt. One way to find out is see if the file got opened.

    inData.open("datfile1.txt");
    if (!inData)
    {
    cout << "Could not open file.\n";
    return 0;
    }

    It would be a good idea to make your main():
    int main()

  8. #8
    Registered User mol's Avatar
    Join Date
    Oct 2001
    Posts
    19
    Thanks swoopy. I caught all my init stuff. That was just a dumb mistake. I know that the file is being found because it actually performs the first loop and outputs to the file. The other loop is when it crashes. Of course, if I comment out the first loop and just run the second then that one works. Sorry everyone. I am just trying to figure out file i/o.
    mol
    aka version2

    life is just 1's and 0's

  9. #9
    Registered User mol's Avatar
    Join Date
    Oct 2001
    Posts
    19
    *tears hair out*

    No one has any other ideas?
    mol
    aka version2

    life is just 1's and 0's

  10. #10
    Registered User
    Join Date
    Aug 2001
    Posts
    155
    Don't have my compiler available at this time to run your code. If you haven't figured it out by time I have it available I will compile it and let you know.

    For now I would try placing a series of cout statements after each critical step to see exactly where things are getting hung up when you try to run the entire program.

    PHP:--------------------------------------------------------------------------------
    #include <iostream>
    #include <fstream>

    using namespace std;

    int main()
    {
    int count = 0;
    int num = 0;
    int total = 0;
    int avg = 0;

    ifstream inData;
    ofstream outData;

    inData.open("datfile1.txt");
    outData.open("outdata.txt");

    // check if the open calls actually succeeded !!!
    if(!infile)
    {
    cout << "unable to open file on first attempt" << endl;
    }

    while(inData >> num)
    {
    outData << num << " ";
    cout << num << " ";
    }

    outData << endl;
    cout << endl;

    inData.close();

    // lets get the avg of all ints in the file

    inData.open("datfile1.txt");

    if(!infile)
    {
    cout << "unable to open file on second attempt" << endl;
    }


    while(inData >> num)
    {
    outData << num << " ";

    total += num;
    cout << num << endl;
    count++;
    cout << count << endl;
    }

    avg = total/count;

    outData << endl << avg << endl;
    cout << avg << endl;

    inData.close();
    outData.close();

    return 0;
    }

    I also might try using a second ifstream to read in the second time or commenting out the first call to inData.close() and the second call to inData.open().

    I might also try making sure inData closed when it should have by commenting out the second call to inData.open() and see if you get the appropriate cout statement. You probably should comment out the second while loop if you do this though.

    Good luck. I'll try to check back later.

  11. #11
    Registered User
    Join Date
    Sep 2001
    Posts
    25
    Kinda new at file io but doesn't the first instance of a stream being attached to a file make it read and write protected from other streams unless specified not to be?

  12. #12
    Registered User mol's Avatar
    Join Date
    Oct 2001
    Posts
    19
    guest, thx for the code help.

    I tried outputting to the screen to see exactly where the failure was and it is indeed upon 'opening' the file the second time. Now, why it is not closing/opening properly is beyond me. I just dont see it. Do I need to set a delay or something?

    *shakes head*

    Im telling you guys, you just dont have this kind of trouble with microcontrollers.
    mol
    aka version2

    life is just 1's and 0's

  13. #13
    Registered User
    Join Date
    Aug 2001
    Posts
    155
    I pasted and compiled the code with all the couts listed. It ran fine. Then I took all the couts out and just ran the basic program. It ran and gave correct calculation of file (well, I did change avg to type float, but that doesn't matter much.) I use B4.52 as my IDE. I looked up the member functions for ifstreams. open() is listed, but close() is not. I looked up close() in my reference text, and it is clearly used in programs there in conjunction with ifstreams. I commented out the second call to inData.open() and it crashed. I used tellg() to find out the file cursor position at the end of the first while loop and then again after opening the file for the second time. The file positions were appropriate (at least the file pointer position went from 33 after the first loop and before closing inData to 0 after opening the file for the second time).

    Maybe you can try retyping the lines with close() and the second call to inData.open(). Otherwise I am flumuxed, too. The code looks correct.

  14. #14
    Registered User mol's Avatar
    Join Date
    Oct 2001
    Posts
    19
    Well, I am getting a runtime error when I try to run the code above. In fact, I get the error for not being able to open the file the second time. Then the division by zero error crashes it since the file was never read the second time.

    I didnt think file i/o was this complicated.
    mol
    aka version2

    life is just 1's and 0's

  15. #15
    Registered User
    Join Date
    Aug 2001
    Posts
    155
    If you know anybody with the same compiler you are using you can try your source code there. If your source code runs on a different compiler, then I suspect you have an error in the software of your compiler.

    As I said, your code closing and reopening the ifstream seems to work fine on my compiler.


    You could try resetting the file pointer using seekg() rather than closing and reopening the file, although I have to say I had trouble trying to do that when I was goofing around with the code. If you want to try it, look up what header seekg() is in and #include it. then comment out the call to close() and the second call to inData.open(). Place the line:

    inData.seekg(0);

    immediately after the commented out call to open(). And try compiling/running.

    Are you sure the code you initially posted is symbol for symbol the same as the code you are trying to run?

    Being self_taught I used to run into these sorts of snafu's all the time. Getting better now, though still a lot to learn.

    Idn't life wunerful?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. asynchronized I/O == multiplexing I/O?
    By George2 in forum C Programming
    Replies: 1
    Last Post: 07-24-2006, 10:06 AM
  2. why page based I/O can improve performance?
    By George2 in forum C Programming
    Replies: 1
    Last Post: 06-12-2006, 07:42 AM
  3. more fstream problems
    By howzer in forum C++ Programming
    Replies: 2
    Last Post: 03-15-2006, 06:17 AM
  4. Having Buffer Problems With Overlapped I/O --
    By Sargera in forum C++ Programming
    Replies: 0
    Last Post: 02-07-2006, 04:46 PM
  5. Nonblocking I/O
    By fnoyan in forum Linux Programming
    Replies: 4
    Last Post: 11-29-2005, 04:37 PM