Thread: reading file?

  1. #1
    Registered User
    Join Date
    Nov 2001
    Posts
    11

    reading file?

    Hi;

    How can I read a file like below and calculate the contents:

    File(abc.txt)
    2.0 2.2 4.5
    3.0 3.2 2.5
    4.0 4.2 3.5

    etc....where each row is the value of x1, x2 x3 and values are around 100 for each x1,x2,x3....

    The question is how can I read each values from this file and use them for my calculation...?

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    Same as any other text file - fgets() to read each line and sscanf() to pull it apart
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Apr 2004
    Posts
    9
    in this situation, I think that the atoi() function could be useful (someone correct me if i'm wrong)

    If your text file contains numbers, atoi() lets you convert them to integer format for use in your program.

    Refrence: http://www.iota-six.co.uk/c/i2_feof_fgets_fread.asp

  4. #4
    Registered User linuxdude's Avatar
    Join Date
    Mar 2003
    Location
    Louisiana
    Posts
    926
    if anything it would be atof but the sscanf will stop that.
    Code:
    fgets(buffer,sizeof buffer,file);
    sscanf(buffer,"%f %f %f",&x,&y,&z);

  5. #5
    /*enjoy*/
    Join Date
    Apr 2004
    Posts
    159
    use the library "stdlib.h"
    or use "fstream.h" if you are using visual c++
    Code:
    ....
    openfile(only in read mode)
    ....
    put the contenent of file into array of 2d  //for(lines){for(colums) {@function that allocate numbers into array(matrice)}}
    ....
    @===>a function should control integer (exemple:controle ---->10)

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. opening empty file causes access violation
    By trevordunstan in forum C Programming
    Replies: 10
    Last Post: 10-21-2008, 11:19 PM
  2. Formatting the contents of a text file
    By dagorsul in forum C++ Programming
    Replies: 2
    Last Post: 04-29-2008, 12:36 PM
  3. Replies: 3
    Last Post: 03-04-2005, 02:46 PM
  4. Possible circular definition with singleton objects
    By techrolla in forum C++ Programming
    Replies: 3
    Last Post: 12-26-2004, 10:46 AM
  5. System
    By drdroid in forum C++ Programming
    Replies: 3
    Last Post: 06-28-2002, 10:12 PM