Code:
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 150
int main (void)
{
/* By using variables starting with "str" the
** C standard doesn't guarantee your program to
** work at any time.
*/
char fstr[MAXSIZE];
FILE *infp;
int count = 0;
/* perror is specially designed to report errors
** after a library function fails. It gives more
** information than a homegrown error report in
** most cases and is easier to use. Also, 1 is
** a non-standard exit condition for main, the
** three portable values are 0, EXIT_SUCCESS, and
** EXIT_FAILURE. The last two are found in stdlib.h.
*/
if((infp = fopen("input.txt", "rt"))== NULL) {
perror("Unable to open input file");
exit(EXIT_FAILURE);
}
printf("\nNow counting number of records on file");
/* When reading lines you don't want to use scanf,
** that isn't what it is designed for. fgets on the
** other hand is very well suited to this task and
** results in shorter code if you've noticed.
*/
while(fgets(fstr, sizeof fstr, infp)!= NULL)
count++;
printf("\n\nNumber of records on file is %d", count);
getchar();
fclose(infp);
/* Personal preference: If I use EXIT_FAILURE
** anywhere in my programs, I'll use the corresponding
** macro EXIT_SUCCESS when I return from main. It just
** looks neater.
*/
return EXIT_SUCCESS;
}
>For example, "one" is a word and "meaning of one" is a
>meaning of one. How would I divide each line into two pieces so
>I can have word and meaning separately?
The easiest way is to use a delimiting character which is not in the data itself to divide the line. This way you can use sscanf, strtok, and similar functions to break up the string:
one : meaning of one
Code:
if ( fgets ( a, sizeof a, file ) != NULL )
sscanf ( a, "%s : %[^\n]", b, c );
It's also usually a good idea to double check that sscanf executed properly so that you can work out errors as close to the source as possible.
-Prelude