Reading and writing to file

Discussion in 'Mac Programming' started by farmerdoug, Feb 4, 2011.

  1. farmerdoug macrumors 6502a

    Joined:
    Sep 16, 2008
    #1
    The fprintf inserts the sum/200 later than it is supposed to and part of the original file disappears. I imagine that it has to with timing of the various steps. Any way I can make this work?
    Thanks

    Code:
     for(l = 0; l < numstocks; l++)
                    {
                    rewind(stocks[l]);
                    sum = 0;
                    for (i = 0; i < 200; i ++)
                        {
                        k = fscanf(stocks[l],"%s %f ", date, price[i]);
                        sum += *price[i];
                        }
                    fprintf(stocks[l],"     %6.3f\n", sum/200); 
                  
                    }
    
     
  2. balamw Moderator

    balamw

    Staff Member

    Joined:
    Aug 16, 2005
    Location:
    New England
    #2
    Might help to explain what it is you expect to happen.

    B
     
  3. lee1210 macrumors 68040

    lee1210

    Joined:
    Jan 10, 2005
    Location:
    Dallas, TX
    #3
    maybe fflush? Or fclose to force a flush if you're done with the file?

    -Lee
     
  4. balamw Moderator

    balamw

    Staff Member

    Joined:
    Aug 16, 2005
    Location:
    New England
    #4
    Personally, I'd do it as two operations if I understand what is supposed to happen. open the file read only, and read it, close the file and open the file for append and append the summary line.

    If that's what's supposed to happen.

    B
     
  5. ender land macrumors 6502a

    Joined:
    Oct 26, 2010
    #5
    That seems plausibly what it is trying to do and what I also gather from the OP :)
     
  6. farmerdoug thread starter macrumors 6502a

    Joined:
    Sep 16, 2008
    #6
    thanks guys.
    If I use ftell and fseek, I can get the float inserted in the right place but I still overwrite part of next line. I need to use a second buffer to store the end of the file and then rewrite it back into the original file.
     
  7. subsonix macrumors 68040

    Joined:
    Feb 2, 2008
    #7
    Out of curiousity, how many files do you have open simultaneously here, 'numstocks' I presume, but how many is that?
     
  8. farmerdoug thread starter macrumors 6502a

    Joined:
    Sep 16, 2008
    #8
    right now - 50.
    Instead of reading the data in and then going back do the calculations, I am doing it all at once.
     

Share This Page