Reputation: 175
So I have this function to find the longest line in a file:
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;
}
and I was thinking of combining it with this one:
bool startsWith(const char *pre, const char *str)
{
size_t lenpre = strlen(pre),
lenstr = strlen(str);
return lenstr < lenpre ? false : strncmp(pre, str, lenpre) == 0;
}
But.. however, the LongestLine()
function returns an integer. So how can I use both functions so that I may find the longest line starting with let's say //
?
Upvotes: 0
Views: 143
Reputation: 49813
Add a call to startsWith
(to see if it is a comment) in your if
statement to decide if a line is the new longest:
if( startsWith("//",buf) && (line_len < len_tmp) ) {
Upvotes: 1