Thread: Take data from a file and store in array or structure

  1. #1
    Registered User
    Join Date
    Apr 2011

    Take data from a file and store in array or structure

    I have a project where I need to take different input files and then store different fields and then do some math/calculations on them.

    The trick is some of the files have 0 to 4 line headers which need to be ignored. Also, each line has different field lengths.

    Here's an example of part of an input file (4 line header):

    .i 9
    .o 1
    .p 87
    0-111-00- 001
    01-110-0- 010
    11-100-0- 100

    I need to be able to ignore the header, and then take the first part of the line (0-111-00-) and place into one field and take the (001) into another field.

    I guess I would check the file for number of lines first to allocate the array size and then count characters until I hit a space/blank to determine field length?

    Here's what I have so far, but am pretty much lost after that!!

    #include  <stdio.h>
    #include  <string.h>
    int main(int argc, char *argv[]) 
    FILE        *fname;
    long        num_nodes; 
    /* Open the file */
      fprintf(stderr,"main: no filename given in command line\n");
    fname = fopen(argv[1],"r");
    if (!fname)
       fprintf(stderr,"main:  cannot open file \"%s\"\n",argv[1]);
     /* Parse the file */
     return 0;}

    Thanks for the help!

  2. #2
    Registered User
    Join Date
    Nov 2010
    Long Beach, CA
    Care to tell us what exactly you're stuck on? Have you read any tutorials on file processing? We have one here, and Google has tons more. What about class notes and text book? Surely you have some reference material on how to read lines from a file and extract data. Here's a couple big hints: fgets() and sscanf(). Start simply, by just making the program read a line and echo it out. Then, try extracting significant parts of that line and echoing those out separately, thus working your way up to solving the actual problem at hand. So, go take a crack at it, and come back when you're really stuck, not just lazy stuck (as Tater would say). Post a real attempt at solving this (just opening a file doesn't count), and tell us what specifically you're having trouble with, and we'll help you out.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Read values from txt file and store them in structure
    By bojomojo in forum C Programming
    Replies: 6
    Last Post: 12-19-2010, 10:36 AM
  2. What's an acceptable file to store mesh data on?
    By shrink_tubing in forum C++ Programming
    Replies: 9
    Last Post: 07-02-2010, 04:10 PM
  3. Pick data from file store in array
    By swgh in forum C Programming
    Replies: 1
    Last Post: 07-10-2009, 09:57 AM
  4. Data Structure to store unlimited dynamic vectors
    By m3rk in forum C++ Programming
    Replies: 8
    Last Post: 04-22-2009, 06:12 AM
  5. Replies: 1
    Last Post: 03-27-2009, 04:21 AM