reading from a file.sorting

Richard Barnette barnettr at snaggle.rtp.dg.com
Fri Apr 5 04:20:11 AEST 1991


In article <1991Apr3.100911.29842 at milton.u.washington.edu> amigo at milton.u.washington.edu (The Friend) writes:
>>amigo at milton.u.washington.edu (The Friend) writes:
>>
>>
>       I'm looking for a simple program that'll read ten words from a
>  string that has only got spaces between the words. I
>  had one example that had pointers - data read in via fscanf,
>  then the pointer was copied to another pointer array (each array
>  held one word). After the 10 words were read, the array was simply 
>  incremented backwards in a for loop to print out correctly.
>>
>  I have [REVISED]:
>>
>>
>       FILE *fp;
>       static char *data_array[11];
>       int i;
>       main(){
>               fp=fopen("test","r");          
>               for(i=0;i<10;i++){
>                      fscanf(fp,"%s", data_array[i]);
>                      printf("%d  %s",i,data_array[i]);   /* test to see 
>>                                             anything's put in data_array[] */
>                                }
>>
    The pointers in data_array are all NULL; they don't point to anything.
In order save the data read by fscanf() you'll need to allocate space.
    Try this


       #include <string.h>

       FILE *fp;
       static char *data_array[11];
       int i;
       main(){
	       char data[32]; /* 31 letters in word + null byte */
               fp=fopen("test","r");
               for(i=0;i<10;i++){
                      fscanf(fp,"%s", data);
		      data_array[i] = strdup(data);
		      }

    strdup() is a standard library function declared in string.h

    Note also, data_array will hold 11 items, but the for loop will only
initialize 10 of them; the 11th is unused.

Richard Barnette      | Data General Corporation | obligatory (in)famous quote:
(919) 248-6225        | RTP, NC  27709	         |  You wascal wabbit!
Commercial Languages  | 62 T.W. Alexander Drive	 |  Wandering wizards won't
barnettr at dg-rtp.dg.com				 |  win! - /usr/lib/sendmail



More information about the Comp.lang.c mailing list