My .dat file will contain information like below.
///////////
First
[...]
In my main program, it will open this dat file, read line by line.
When it hits the string I'm searching for (e.g. "First"), the program
will know that the next line will be the variables to be stored. Are
there any C function to read file line by line? Please give me some
clue. Thanks a lot.
You can try using fgets() as suggested by others, but it requires you
to make choices about the target buffer size before you read each
line. I.e., either your solution is convoluted and has a built in
buffer growing algorithm, or it has a buffer overflow, or it just
behaves incorrectly for inputs that are too large. If you have a very
strict way in which your input files are constructed then you can get
away with a fixed buffer algorithm, of course.
The alternative is to use a string library that takes care of this for
you. There are many string libraries that can work for you, but let
me just suggest how it might be done with my own called the "better
string library" (
http://bstring.sf.net/):
Alternative 1: A high performance streaming solution (but it will read
ahead, which may be inappropriate for your application)
FILE * fp = fopen (inputFileName, "r");
if (fp) {
bStream s = bsopen ((bNread) fread, fp);
bstring b = cstr2bstr ("");
while (BSTR_OK == bsreadln (b, s, '\n')) {
/* b->data is an "unsigned char *" pointing to a line */
}
bdestroy (b);
bsclose (s);
fclose (fp);
}
Alternative 2: A slow but simpler streaming solution (the file reading
is exact)
FILE * fp = fopen (inputFileName, "r");
if (fp) {
bstring b;
while ((b = bgets ((bNgetc) fgetc, fp, '\n')) != NULL) {
/* b->data is an "unsigned char *" pointing to a line */
bdestroy (b);
}
fclose (fp);
}
Alternative 3: Just read the whole thing and parse it afterward (if
you have to read and hold the whole file anyway, this is probably the
fastest solution and gives you indexed random access to the lines.)
FILE * fp = fopen (inputFileName, "r");
bstring b;
if (fp) {
bstring b = bread ((bNread) fread, fp);
struct bstrList * bl = bsplit (b, '\n');
int i;
if (bl) for (i=0; i < bl->qty; i++) {
/* bl->entry
->data is pointing to a line */
}
bstrListDestroy (bl);
bdestroy (b);
fclose (fp);
}
None of the alternatives shown above have any risk of buffer overflow
(though apparently they might not work correctly on the Tandom NonStop
or Data General Eclipse computers, but if you are on such a machine
you practically already know this and you have my greatest sympathy
and there is a simple way to work around the problem as described in
the documentation) and as shown there will be no memory leaks. Even
attempts at out-of-memory and input stack smashing attacks cannot
happen.
As to parsing the lines, the "better string library" has functions
like biseq, bCaselessCmp, bsplit, binstr, binchr etc and because of
its direct interoperability with char * buffers, you can use C
standard library functions like atoi, sscanf, and so on with no issue.