schmitsz
schmitsz

Reputation: 175

Find shortest line in file C

So far I managed to get the longest line in a file like this:

int LongestLine(FILE *filename) {

  char buf[MAX_LINE_LENGTH] = {0};

  char line_val[MAX_LINE_LENGTH] = {0};
  int line_len = -1;
  int line_num = -1;
  int cur_line = 1;

  filename = fopen(filename, "r");

  while(fgets(buf, MAX_LINE_LENGTH, filename) != NULL) {
    int len_tmp = strlen(buf) - 1;

    if(buf[len_tmp] == '\n')
      buf[len_tmp] = '\0';

    if(line_len < len_tmp) {
      strncpy(line_val, buf, len_tmp + 1);
      line_len = len_tmp;
      line_num = cur_line;
    }

    cur_line++;
  }

  return line_num;
}

However, finding the shortest is gonna be slightly different using this logic. I can't just write: if(line_len > len_tmp). How can I apply the same logic but for finding the shortest line in a file? Even a pseudo-code would do.

Upvotes: 0

Views: 584

Answers (2)

Persixty
Persixty

Reputation: 8589

How about

int line_len = MAX_LINE_LEN+1;

At the start to make sure the first line you read is shorter than the 'stored' shortest line-length.

int LongestLine(FILE *filename) {

  char buf[MAX_LINE_LENGTH] = {0};

  char line_val[MAX_LINE_LENGTH] = {0};
  int line_len = MAX_LINE_LEN+1; //Set initial shortest line to big number.
  int line_num = -1;
  int cur_line = 1;

  filename = fopen(filename, "r");

  while(fgets(buf, MAX_LINE_LENGTH, filename) != NULL) {
    int len_tmp = strlen(buf); 

    if(len_tmp>0 && buf[len_tmp-1] == '\n') {
      buf[len_tmp-1] = '\0';
      --len_tmp;
    }

    if(len_tmp >0 && line_len > len_tmp) {  //On first pass that encounters a non-empty line this will always trigger because of the read limit in fgets.
      strncpy(line_val, buf, len_tmp + 1);
      line_len = len_tmp;
      line_num = cur_line;
    }

    cur_line++;
  }

  return line_num;
}

Consider how the wider program should handle an entirely empty file or file of all blank lines. that code will return MAX_LINE_LENGTH+1 in such a condition. That may or may not suit your purpose.

Also it's not clear why your taking a copy of the shortest line and its line number. You do nothing with them and don't return them from the function. What good do the following lines do?

      strncpy(line_val, buf, len_tmp + 1);

      line_num = cur_line;

Upvotes: 2

Karthikeyan.R.S
Karthikeyan.R.S

Reputation: 4041

Make the condition like this.

if( line_num==-1)
    line_len=len_tmp;
else if ( len_tmp < line_len){
     line_num=len_tmp;
    // do the code for getting that line.}

Upvotes: 0

Related Questions