Solved

Reading Text File Entries into an Array

Posted on 1998-01-19
2
250 Views
Last Modified: 2010-04-02
I need to be able to read an 'x' line test datafile containing several numbers, i.e.

12.3
13.4
17.6
18.1

I need to read this into an array of strings or floats (doesn't matter which).

Is there a quick way to do this ?

Thanks for any help you can offer.

James
0
Comment
Question by:jatkin
2 Comments
 
LVL 16

Accepted Solution

by:
imladris earned 50 total points
ID: 1257018
The difficulty you are aniticipating, I think, is that you don't know how many lines there are in the file. I would propose counting them, then allocating the array, go back to the beginning and then read them in:

#include "stdio.h"

main()

{   FILE *fp;
    char line[80];
    int i,ln;
    float *num;

    ln=0;
    fp=fopen("file","rb+");
    while(fgets(line,80,fp)!=NULL)++ln;
    fseek(fp,0L,SEEK_SET);
    num=malloc(ln*sizeof(float));
    for(i=0; i<ln; ++i)fscanf(fp,"%f\n",num+i);
    fclose(fp);
    exit(0);
}

(All error checking left out for readability and simplicity).

0
 
LVL 4

Author Comment

by:jatkin
ID: 1257019
An interesting solution.
Thanks.

James
0

Featured Post

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Finding a good hash function 4 120
How to issue a linefeed, pause, and clear screen in UNIX enviroment 3 69
An API detour question 7 79
Why is compiler in oracle server ? 9 46
An Outlet in Cocoa is a persistent reference to a GUI control; it connects a property (a variable) to a control.  For example, it is common to create an Outlet for the text field GUI control and change the text that appears in this field via that Ou…
Windows programmers of the C/C++ variety, how many of you realise that since Window 9x Microsoft has been lying to you about what constitutes Unicode (http://en.wikipedia.org/wiki/Unicode)? They will have you believe that Unicode requires you to use…
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use nested-loops in the C programming language.
The goal of this video is to provide viewers with basic examples to understand opening and reading files in the C programming language.

864 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now