reading from a file to make an array using C -
how make array reading .txt file??
i'm making bidding(auction) program. need read integers .txt , use in array. confused how go in program. txt follows:
100 15 200 20 300 25 400 30 500 35
it recommended show one's own effort while asking question. however, give jump start, please find couple of solutions below.
one possible illustrative solution using static array in solution 1 below. assumption in solution below number of elements known , less 32. if wish keep dynamic, have implement solution using linked list in solution 2 below.
solution 1: fixed array based approach
int main() { file *finp; int somearr[32]; int i, ctr = 0; finp = fopen("haha.txt", "r"); if(null == finp) { printf("unable open file\n"); exit(-1); } while((!feof(finp)) && (ctr < 32)) { fscanf(finp, "%d ", &somearr[ctr++]); } for(i = 0; < (ctr -1); i++) { printf("%d==>", somearr[i]); } printf("%d\n", somearr[i]); fclose(finp); //close file pointer return 0; } the expected output of program
100==>15==>200==>20==>300==>25==>400==>30==>500==>35
solution 2: linked list based solution
further earlier comment, please find alternative dynamic solution doesn't require prior knowledge on number of elements below.
typedef struct node { int value; struct node *next; }node; void createlist(file *finp, node **headbase) { node *currnode; node *head = *headbase; node *tail; while(!feof(finp)) { currnode = malloc(sizeof(struct node)); fscanf(finp, "%d ", &currnode->value); currnode->next = null; if(null == head) { head = currnode; tail = currnode; } else { tail->next = currnode; tail = currnode; } } //store updated head pointer *headbase = head; } void printlist(node **headbase) { node *tmpnode = *headbase; while(tmpnode->next != null) { printf("%d-->", tmpnode->value); tmpnode = tmpnode->next; } printf("%d\n", tmpnode->value); } void deletelist(node **headbase) { node *head = *headbase; node *tmp; while(null != head) { tmp = head; // temp pointer head = head->next; // move head pointer tmp->next = null; // break link printf("<< deleted node: %d\n", tmp->value); free(tmp); } // store head pointer should null *headbase = head; } int main() { file *finp; node *head = null; finp = fopen("haha.txt", "r"); if(null == finp) { printf("unable open file\n"); exit(-1); } createlist(finp, &head); printlist(&head); deletelist(&head); fclose(finp); return 0; } the expected output of program
100-->15-->200-->20-->300-->25-->400-->30-->500-->35 << deleted node: 100 << deleted node: 15 << deleted node: 200 << deleted node: 20 << deleted node: 300 << deleted node: 25 << deleted node: 400 << deleted node: 30 << deleted node: 500 << deleted node: 35
Comments
Post a Comment