Skip to content

Instantly share code, notes, and snippets.

@Meithal
Created April 22, 2018 19:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Meithal/edf34d04de4a75ddbfdcf40f1d6c3a98 to your computer and use it in GitHub Desktop.
Save Meithal/edf34d04de4a75ddbfdcf40f1d6c3a98 to your computer and use it in GitHub Desktop.
split a a string into array of stings with C
/**
* Meithal @github
*
* Splits a string into several strings every new line and return a pointer to the first one
* The very last string will be \0
* Will be ub for lines > 50
* Doesn't free
* Doesnt check for several functions return values
*/
char ** string_into_arrays(char * string) {
int nb_of_words = 0;
for (char *letter = string; *letter != '\0'; letter++)
if (*letter == '\n')
++nb_of_words;
char ** array_words = calloc((size_t) nb_of_words + 2, sizeof(char *));
for(
char
* start = string,
**word = array_words - 1,
position_letter = 0;
*string != '\0' ;
string++
)
{
if(string == start || *string == '\n') {
word ++;
*word = malloc(50);
memset(*word, 0, 50);
position_letter = 0;
}
if(*string == '\r' || *string == '\n')
continue;
else {
(*word)[position_letter++] = *string;
}
}
return array_words;
}
int main() {
FILE * fwords = fopen("words.txt", "rb");
if (fwords == NULL) {
puts("System failure opening the word file\n");
return EXIT_FAILURE;
}
fseek(fwords, 0L, SEEK_END);
size_t file_size = (size_t) ftell(fwords);
rewind(fwords);
char* words = malloc(file_size);
fread(words, sizeof(char), file_size, fwords);
fclose(fwords);
fwords = NULL;
char ** arr_words = string_into_arrays(words);
int number_of_words = 0;
while (arr_words[number_of_words] != NULL )
puts(arr_words[number_of_words++]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment