Skip to main content

1-16

Quest: page 30


Revise the main routine of the lonigest-line program so it will correctly print the length of arbitrarily long input lines, and as much as possible of the text.


I understood this problem like this:

  • count characters longer than the defined 1000 and then print 1000 order more characters of that input. i've chosen unsigned long int which has the max value of (1 << 64) -1.

gen test data

note

i wrote two lines in the txt file.

  • line one: 65535 chars long
  • line two: 100 chars long
#include <stdio.h>
#include <stdlib.h>

#define MAX 0xFFFF

int main() {
FILE *f = fopen("txt", "w");
if (f == NULL) {
return EXIT_FAILURE;
}
// printf w MAX times
for (unsigned short i = 0; i < MAX; i++) {
fprintf(f, "w");
}
fprintf(f, "\n");
for (int i = 0; i < 100; i++) {
fprintf(f, "w");
}
fprintf(f, "\n");

fclose(f);
return EXIT_SUCCESS;
}
caution

the program will fail when one line is longer than UINT64_MAX. To avoid these i need either a bigger int type 128 bits or 256 bits for extended boundries OR check if we are already at maxvalue each step...

#include <stdio.h>
#include <stdlib.h>

#define MAX 1000
#define UINT64_MAX 0xFFFFFFFFFFFFFFFF
// this actually works but the compiler will give a warning that the shifted
// value is one too much that is why i have chosen to use the hex presentation
//#define UINT64_MAX (1ULL << 64) -1

unsigned long int gl(char line[], int maxline);
void cp(char to[], char from[]);

int main() {
unsigned long int max;
unsigned long int len;
char line[MAX];
char longest[MAX];
max = 0;
while ((len = gl(line, MAX)) > 0) {
if (len > max) {
max = len;
cp(longest, line);
}
}
if (max > 0) {
printf("%s", longest);
if (max > 1000) {
printf("...\n");
}
printf("longest line: %lu\n", max);
}
return EXIT_SUCCESS;
}

unsigned long int gl(char s[], int lim) {
int c;
int lastchar = 0;
unsigned long int i;
for (i = 0; (c = getchar()) != EOF && c != '\n'; i++) {
if (i < lim - 1) {
// save max lim chars
// but count further and discard the rest
s[i] = c;
lastchar = i;
}
}
if (c == '\n') {
s[lastchar] = c;
lastchar++;
}
s[lastchar] = '\0';
return i;
}

void cp(char to[], char from[]) {
int i;
i = 0;
while ((to[i] = from[i]) != '\n') {
++i;
}
}