Thread: Reading text file twice, can it be done once?

  1. #1
    Registered User
    Join Date
    Jan 2006
    Posts
    9

    Reading text file twice, can it be done once?

    I am reading a text file of two-column numeric data. I do not know the number of rows that the file will contain. Currently, I read the file twice: Once to ascertain the length and the second time to fill the arrays with the data. Is there a way to create and populate the arrays while only having to read the text file once?

    Here is my current code:
    Code:
    FILE* fid;
    double tempx, tempy;
    
    fid = fopen("c:/file.txt","rt");
    int i=0;
    while( fscanf(fid,"%le%le", &tempx, &tempy )!= EOF )
    	i++;
    rewind( fid );
    
    x = new double[i];
    y = new double[i];
    
    i=0;
    while (fscanf(fid,"%le%le", x+i, y+i)!= EOF)
    	i++;
    fclose(fid);
    Thanks for your time.

  2. #2
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    Code:
    x = new double;
    That's C++.

    If you're using C, go with realloc().
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  3. #3
    Registered User
    Join Date
    Jan 2006
    Posts
    9

    realloc

    Good point, I really should have posted this in c++, but I was hesitant, because I wanted to stick with C file handling rather than c++ file handling.

    I'll move the post to the c++ board.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Formatting the contents of a text file
    By dagorsul in forum C++ Programming
    Replies: 2
    Last Post: 04-29-2008, 12:36 PM
  2. Inventory records
    By jsbeckton in forum C Programming
    Replies: 23
    Last Post: 06-28-2007, 04:14 AM
  3. C++ std routines
    By siavoshkc in forum C++ Programming
    Replies: 33
    Last Post: 07-28-2006, 12:13 AM
  4. Reading Character at a time from a text file
    By Giania in forum C Programming
    Replies: 8
    Last Post: 02-25-2006, 03:17 PM
  5. A bunch of Linker Errors...
    By Junior89 in forum Windows Programming
    Replies: 4
    Last Post: 01-06-2006, 02:59 PM