c - How to read a file of names into an array -
i need help reading in list of names , storing them string. allocated memory strings, need help reading them , storing them in. here info , code written. need help insert_data
function.
#include <string.h> #include <stdio.h> #include <stdlib.h> #define max_string_len 25 void insert_data(char **strings, const char *filename, int size); void allocate(char ***strings, int size); int main(int argc, char* argv[]){ if(argc != 4){ printf("wrong number of args"); } char **pointer; int size = atoi(argv[1]); allocate(&pointer, size); insert_data(pointer, argv[2], size); } void allocate(char ***strings, int size){ int i; *strings = (char**) malloc(sizeof(char**) * size); for( = 0; < size; i++) { (*strings)[i] = malloc(sizeof(char) * max_string_len); } }
this function need help with:
void insert_data(char **strings, const char *filename, int size){ file *input; input = fopen(filename, "r"); int i; (i = 0; < size; i++){ fscanf(input,"%s", (*strings)[i]); } fclose(input); }
here list reading in:
class="lang-none prettyprint-override">matt susan mark david aden phil erik john caden mycah
#include <string.h> #include <stdio.h> #include <stdlib.h> #define max_string_len 25 #define _s(x) #x #define s(x) _s(x) void insert_data(char **strings, const char *filename, int size); void allocate(char ***strings, int size); int main(int argc, char* argv[]){ if(argc != 3){ printf("wrong number of args\n"); printf("usage:%s size filename\n", argv[0] ? argv[0] : "prog"); exit(-1); } char **pointer; int size = atoi(argv[1]); allocate(&pointer, size); insert_data(pointer, argv[2], size); int i; for(i=0;i<size;++i){ printf("%s\n", pointer[i]); free(pointer[i]); } free(pointer); homecoming 0; } void allocate(char ***strings, int size){ int i; *strings = malloc(sizeof(char*) * size); for( = 0; < size; i++) { (*strings)[i] = malloc(sizeof(char) * (max_string_len+1)); } } void insert_data(char **strings, const char *filename, int size){ file *input= fopen(filename, "r"); int i; (i = 0; < size; i++){ fscanf(input,"%" s(max_string_len) "s", strings[i]); } fclose(input); }
c string fscanf
No comments:
Post a Comment