Solved

Reading Text File Entries into an Array

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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

This tutorial is posted by Aaron Wojnowski, administrator at SDKExpert.net.  To view more iPhone tutorials, visit www.sdkexpert.net. This is a very simple tutorial on finding the user's current location easily. In this tutorial, you will learn ho…
This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so…
The goal of this video is to provide viewers with basic examples to understand and use structures 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.

749 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