Skip to content

Instantly share code, notes, and snippets.

@gynvael
Last active May 26, 2022 15:23
Show Gist options
  • Select an option

  • Save gynvael/837a96ee1c8eff9bf8087d988a6dcad9 to your computer and use it in GitHub Desktop.

Select an option

Save gynvael/837a96ee1c8eff9bf8087d988a6dcad9 to your computer and use it in GitHub Desktop.
And yet one more way to do it
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define ARR_SZ 1024
#define _TOSTR(a) #a
#define TOSTR(a) _TOSTR(a)
int main()
{
FILE *f = fopen("ctext.txt", "rb");
if (f == NULL) {
fprintf(stderr, "error opening the file\n");
return 1;
}
fseek(f, 0, SEEK_END);
size_t sz = ftell(f);
fseek(f, 0, SEEK_SET);
char *data = malloc(sz + 1);
fread(data, 1, sz, f);
data[sz] = '\0';
char *longest = NULL;
char *current = NULL;
size_t longest_sz = 0;
for (size_t i = 0; i < sz; i++) {
if (current == NULL) {
current = data + i;
}
if (data[i] == ' ' || data[i] == '\t' ||
data[i] == '\n' || data[i] == '\r') {
data[i] = '\0';
size_t current_sz = (size_t)(&data[i] - current);
if (current_sz > longest_sz) {
longest = current;
longest_sz = current_sz;
printf("found a new longest word: %s\n", longest);
}
current = NULL;
}
}
printf("longest word: %s\n", longest);
printf("longest word size: %i\n", (int)longest_sz); // shh...
free(data);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment