Monday, December 13, 2010

Rhino Skip Rack Pinion

C: read data from text files and discarding comments

Suppose you have a file like this
 # commento1 

value 1 value # 2
commento2
value 3
# comment # comment
3 4 4

value value value
5 6

Suppose you want to extrapolate from it the values \u200b\u200bexcluding the text is unnecessary for the comments.

The following describes a possbile way to do it.
 

# include int main (void) {

static const char filename [] = "file.txt";

FILE * file = fopen (filename, "r");

if (file! = NULL) {

/ * here, 4096 is the maximum line size * /
char line [4096];
int i;

/ * read a line * /
while (fgets (line, sizeof (line), file)! = NULL) {

if (line [0 ]!='#')

{sscanf (line, "value % d \\ n ", & i);
printf ("% d \\ n ", i);
}
}
fclose (file);

}
else
{
perror (filename);
}

return 0;}


The execution of the program described in the input file shown above leads to the following implementation
 
1 2 3


4 5 6


The file is read line by line and comment lines are discarded (recognized by the character '#' first). If this is not the comment, the numeric value is extrapolated from the text string.

IMPORTANT: fgets not always read a line, it reads as many bytes as are specified by the second argument, in the presence of a symbol of "head" stop reading even though the number of bytes specified has not been achieved, and when this happens we can say that a row has been read, but for obvious reasons, you must be sure that the character length of a line does not exceed that specified as the second argument of fgets . Install

0 comments:

Post a Comment