Solved

Reading Text File Entries into an Array

Posted on 1998-01-19
2
253 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

Back Up Your Microsoft Windows Server®

Back up all your Microsoft Windows Server – on-premises, in remote locations, in private and hybrid clouds. Your entire Windows Server will be backed up in one easy step with patented, block-level disk imaging. We achieve RTOs (recovery time objectives) as low as 15 seconds.

Question has a verified solution.

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

Suggested Solutions

Preface I don't like visual development tools that are supposed to write a program for me. Even if it is Xcode and I can use Interface Builder. Yes, it is a perfect tool and has helped me a lot, mainly, in the beginning, when my programs were small…
Examines three attack vectors, specifically, the different types of malware used in malicious attacks, web application attacks, and finally, network based attacks.  Concludes by examining the means of securing and protecting critical systems and inf…
The goal of this video is to provide viewers with basic examples to understand opening and writing to files in the C programming language.
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.

777 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