how do I load text from a data file into an array ?

mml0707
mml0707 used Ask the Experts™
on
Hi, I'm needing some help with a data file. I want to take data from a text file that I have created and load it into an array so that I can search and sort the data, but I'm not quite sure how to do that. I know I need to first open the file for reading, but then do I use fscanf and a file pointer to move through the data and load it into an array that way ?
Can someone tell me if I'm on the right track ?
Thanks!
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Commented:
yes you are
// This code will read data from any text file you choose :).  Hope it helps

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

void main(void)
{
char filename[50],data;          // buffer for file name
char filedata[50000];     // buffer for file data
int i,flen;
FILE *fp;                    // file pointer

printf("Enter filename to read :");
scanf("%s", &filename);
flen = strlen(filename);                  // If filename > 50, Error                              
 
 if (flen > 50)
 {
     printf("Filename too large\n");
 }

 fp = fopen(filename,"r");                    // Open file for a read                              
           if ( (fp == NULL))
           {
            printf("Error in opening the file for reading\n");
         exit(1);
           }
                data = getc( fp );                // Read first char                                        

   i=0;
     while ( !feof( fp ))
        {                                                 // Not end of file, so output                  
               filedata[i] = data;
               printf("%c",filedata[i]);
               data = getc( fp );                // Read the next char                              
               i++;
     }
   fclose(fp);
 }

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial