Ignoring comment lines marked with "%" using open() in C on linux
I am trying to read a file which has the first two lines marked with a "%" as the first character. I need to ign开发者_高级运维ore these two lines, and then read 4 separate integer variables, separated by an unknown amount of white space. This then repeats for each line until EOF. I am attempting to use open() from fcntl.h.
Is there a way to begin reading after 2 full lines, and then separate the 4 values with white space between them into 4 integer variables?
This is a sample file:
% Input file
% number time time2 priority
0 10 4 2
1 8 2 1
2 12 0 5
3 2 4 4
When doing I/O using open() (not library buffered like fopen()), you want to read all the data into RAM, and then process it.
int fd = open("file", O_RDONLY);
if (fd < 0) {
error();
}
long size = lseek(fd, 0, 2);
lseek(fd, 0, 0);
char *data = malloc(size + 2);
read(fd, data, size);
data[size] = 0;
data[size+1] = 0;
close(fd);
Now, parse the file:
char *ptr = data;
while (*ptr) {
char *end = strchr(ptr, '\n');
if (!end) {
end = ptr + strlen(ptr);
}
*end = 0;
if (*ptr != '%') { /* a valid line */
int a, b, c, d;
if (4 != sscanf(ptr, " %d %d %d %d", &a, &b, &c, &d)) {
error();
}
/* do something with the values */
}
ptr = end + 1;
}
精彩评论