reading from a file.sorting
GEMMELL
d0np at jupiter.sun.csd.unb.ca
Wed Apr 3 23:13:20 AEST 1991
>> 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[] */
>> }
One small problem with this code is that no space is allocated for the
strings. fscanf expects a pointer to an array of char that is large enough
to hold the string and a \0 delimiter. So either you would add a malloc
somewheres or maybe set up the data_array to be a 2D array
[11][MAXSTRINGSIZE] where is MAXSTRINGSIZE is your expected max string size.
------------------------------------------
| \ \ \ \ \ /\ |
| / / / / / || |
| \ \ \ \ \ || d0np at jupiter.csd.unb.ca |
| / / / / / || Michael G. Gemmell |
| \ \ \ \ \ || |
| / / / / / ------ |
| \ \ \ \ \ () |
| / / / / / () |
------------------------------------------
More information about the Comp.lang.c
mailing list