Skip to content

Instantly share code, notes, and snippets.

@gynvael
Created May 26, 2022 15:03
Show Gist options
  • Save gynvael/477fd37e514635c97f3e25193873cffa to your computer and use it in GitHub Desktop.
Save gynvael/477fd37e514635c97f3e25193873cffa to your computer and use it in GitHub Desktop.
Find the longest word in the file
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define ARR_SZ 1024
int main()
{
FILE *f = fopen("ctext.txt", "r");
if (f == NULL) {
fprintf(stderr, "error opening the file\n");
return 1;
}
char longest_word[ARR_SZ]; // Assuming there is no word longer than 1024.
int longest_sz = 0;
char temp_word[ARR_SZ];
int temp_i = 0;
int ch;
for (;;) {
ch = fgetc(f);
if (ch == EOF) {
break;
}
if (temp_i >= ARR_SZ - 1) {
fprintf(
stderr,
"oops, words are too long, make the arrays larger\n");
return 1;
}
if (ch == ' ' || ch == '\t' || ch == '\n') {
if (temp_i > longest_sz) {
longest_sz = temp_i;
temp_word[temp_i] = '\0';
strcpy(longest_word, temp_word);
printf("found a new longest word: %s\n", temp_word);
}
temp_i = 0;
continue;
}
temp_word[temp_i++] = (char)ch;
}
printf("longest word: %s\n", longest_word);
printf("longest word size: %i\n", longest_sz);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment