Solved

Reading Text File Entries into an Array

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

NAS Cloud Backup Strategies

This article explains backup scenarios when using network storage. We review the so-called “3-2-1 strategy” and summarize the methods you can use to send NAS data to the cloud

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Test against App 49 138
chcp 65001 File encoding 66 273
Digital Output does not have continuity to ground? 3 100
windows 10 pro lost profile. 10 44
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…
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…
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use while-loops in the C programming language.
The goal of this video is to provide viewers with basic examples to understand how to create, access, and change arrays in the C programming language.

860 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