Solved

Reading Text File Entries into an Array

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

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
posix semaphore deadlock 13 108
distributed computing in Python 4 99
Socket Programming (Unix) 8 99
Global Keyboard Hooks Blocked 4 56
Summary: This tutorial covers some basics of pointer, pointer arithmetic and function pointer. What is a pointer: A pointer is a variable which holds an address. This address might be address of another variable/address of devices/address of fu…
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 while-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.

706 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

18 Experts available now in Live!

Get 1:1 Help Now