Salvatore said:
I need to check if the line that I read in a file is a empty line or a
comment,
so I did:
if (line[0] != '#' && line[0] != ' '
&& (line[0] != '\r' || line[0] != '\n'))
but if I have a file like this:
1: # comment
2: # comment
3:
4:
5:
6: # comment
the line number 3 it's not jumped so the program crashs
comment.txt is open for reading.
line 1 is not blank.
line 2 is not blank.
line 6 is not blank.
comment.txt is closed.
/* BEGIN comment.c */
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <limits.h>
#define SOURCE "comment.txt"
int blank(char *line);
int text_line(FILE *fp, char **line, size_t *size);
int line2string(FILE *fp, char **line, size_t *size);
int line_count;
int main(void)
{
FILE * fp;
char *line;
size_t size;
int rc;
line = NULL;
size = 0;
fp = fopen(SOURCE, "r");
if (fp != NULL) {
puts(SOURCE " is open for reading.");
rc = text_line(fp, &line, &size);
while (rc > 1) {
printf("line %d is not blank.\n", line_count);
rc = text_line(fp, &line, &size);
}
fclose(fp);
puts(SOURCE " is closed.\n");
if (rc == 0) {
puts("realloc problem");
exit(EXIT_FAILURE);
}
} else {
puts(SOURCE " not opened.");
}
return 0;
}
int blank(char *line)
{
unsigned char c = *line;
while (isspace(c) || c != '\0' && !isprint(c)) {
c = *++line;
}
return c == '\0';
}
int text_line(FILE *fp, char **line, size_t *size)
{
int rc;
do {
++line_count;
rc = line2string(fp, line, size);
} while (rc > 0 && blank(*line));
return rc;
}
int line2string(FILE *fp, char **line, size_t *size)
{
int rc;
void *p;
size_t count;
count = 0;
for (rc = getc(fp); rc != EOF; rc = getc(fp)) {
++count;
if (count + 2 > *size) {
p = realloc(*line, count + 2);
if (p == NULL) {
if (*size > count) {
(*line)[count] = '\0';
(*line)[count - 1] = (char)rc;
} else {
ungetc(rc, fp);
}
count = 0;
break;
}
*line = p;
*size = count + 2;
}
if (rc == '\n') {
(*line)[count - 1] = '\0';
break;
}
(*line)[count - 1] = (char)rc;
}
if (rc != EOF) {
rc = count > INT_MAX ? INT_MAX : count;
} else {
if (*size > count) {
(*line)[count] = '\0';
}
}
return rc;
}
/* END comment.c */