Thread: Function to read data from file to array

  1. #1
    Registered User
    Join Date
    May 2002
    Posts
    6

    Function to read data from file to array

    Hi everyone,
    I am writing a function that will read int numbers from a file and store the numbers into an array, but I an having a hard time with it. on of the problems being that I need it to return the number of items stored in the array when it is done, so that i can use it in another function,
    Below is the code. Any pointers and help would be greatly appreciated.


    #include <stdio.h>
    int* readtopps (char fn[]){
    int data[];
    int n,i;
    FILE* fp;

    fp=fopen(fn,"r");
    fscanf(fp,"%d",&n);
    data=(int*)malloc(sizeof(int)*n);
    for (i=0;i<n;i++)
    fscanf(fp,"%f",&data[i]);
    fclose(fp);
    return(data);
    }
    now, I thougth of making it return a structure containing an int(numofelems) and an array(cardnum), but how would i do that?

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Like this
    Code:
    #include <stdio.h> 
    #include <stdlib.h> 
    int* readtopps (char fn[], int *num ){ 
      int *data; 
      int n,i; 
      FILE* fp; 
    
      fp=fopen(fn,"r"); 
      fscanf(fp,"%d",&n); 
      data=malloc(sizeof(int)*n); // if you need the cast, stop using C++
      for (i=0;i<n;i++) 
        fscanf(fp,"%f",&data[i]); 
      fclose(fp);
      *num = n;  // store 'n' where the caller can see it
      return(data); 
    }
    Call it like so
    int num;
    int *ptr;
    ptr = readtopps( "file", &num );

  3. #3
    Registered User
    Join Date
    May 2002
    Posts
    6
    so ptr is a pointer to the array data, right? since that's what readtopps returns.

  4. #4
    Im back! shaik786's Avatar
    Join Date
    Jun 2002
    Location
    Bangalore, India
    Posts
    345
    >so ptr is a pointer to the array data, right? since that's what readtopps returns.
    But take a look at num passed as an extra parameter to readtopps(), you have the number of elements there.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Can we have vector of vector?
    By ketu1 in forum C++ Programming
    Replies: 24
    Last Post: 01-03-2008, 05:02 AM
  2. C++ std routines
    By siavoshkc in forum C++ Programming
    Replies: 33
    Last Post: 07-28-2006, 12:13 AM
  3. <Gulp>
    By kryptkat in forum Windows Programming
    Replies: 7
    Last Post: 01-14-2006, 01:03 PM
  4. Binary Search Trees Part III
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM
  5. HUGE fps jump
    By DavidP in forum Game Programming
    Replies: 23
    Last Post: 07-01-2004, 10:36 AM