Im trying to figure out how to read specific lines from file, ie I have file with 40 lines and I want to print only the lines 3,4,17,24 out from the file, by the line number. What I know right know is just how to print the whole file line by line with a condition of != EOF. What I'm trying to get at the end is a program that can read file's decided lines and print them out. Thanks a lot.
void Analyzer(char* filename, int *rows, int *cols) {
char s[99];
FILE *fin = fopen(filename, "r");
if (fin == NULL)
{
printf("Cannot open file.\n");
return;
}
while (fgets(s, 99, fin) != EOF) {
printf("%s", s);
}
fclose(fin);
}
edit: the next step after that is getting specific colums from the decided lines, What I mean by cloumns is that every line has ',' between colums, my idea was to try with strtok(), but if you got any better idea i'd thank you.
Keep a count of lines read.
int linecounter = 0;
while (fgets(s, 99, fin) != NULL) {
switch (++linecounter){
case 3: case 4: case 17: case 24:
printf("%s", s);
}
}
I also fixed your bug; fgets()
returns NULL
not EOF
on end of file.
A bit off-topic answer: It is a nice exercise to do this in C directly, but it is actually error prone. There are much better tools to filter lines from a file.
ed
and sed
would be my favorites here:
printf %s\\n 3 4 17 24 q| ed txtfile
sed `printf \ \-e%s\ 3p 4p 17p 24p d` < txtfile
or with a list of numbers (output in ed with line numbers)
(cat lnums | while read l; do printf %sn\\n "$l"; done; printf %s\\n q)| ed txtfile
args=`sed -e 's/^[0-9]*$/-e &p/' -e '$a -e d' lnums | tr '\n' ' '`; sed $args txtfile
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.