0

So in my file that gets saved in my program is displayed like

name name number
name name number
name name number
name name number
name name number

I need to get the number of elements in that file, so in this case it should be 5

 FILE *pRead;

int num = 0;

 pRead = fopen("names.dat", "r");

 if ( pRead == NULL )

 printf("\nFile cannot be opened\n");

else



 while ( !feof(pRead) ) {

num++ //add one to num
printf("Num = ",num); //pint the value of num

 } //end loop

That's what I tried but it loops for infinity.

Charles
  • 50,943
  • 13
  • 104
  • 142
SolidCloudinc
  • 329
  • 10
  • 27
  • 3
    Why would it stop if you're not reading anything? – Michael Krelin - hacker Oct 29 '13 at 15:39
  • @MichaelKrelin-hacker It's reading names.dat – SolidCloudinc Oct 29 '13 at 15:40
  • 2
    no, you are just checking if feof is "true" or "false", but there's no fread or fgetc or whatever to "consume" bytes... – ShinTakezou Oct 29 '13 at 15:41
  • @ShinTakezou Okay then I have no idea how to do what I want to do. Any help would be great. – SolidCloudinc Oct 29 '13 at 15:42
  • you want to count lines, so you can `int c; while ( (c = fgetc(pRead)) != EOF) { if (c == 10) num++; } printf("lines %ld\n", num);` which is not perfect way but it works... most of the time:) Just a sketch of the idea. (problems bound to when EOF is returned - combine it with feof -, and if NL char identifies really always a "line" in your file) – ShinTakezou Oct 29 '13 at 15:47
  • 1
    You also didn't define what an "element" is. Is it a single word? A `char` ? A trio of words? Lines? I think you need to think about this some more, and while you're at it, consider the [`fgets()`](http://en.cppreference.com/w/c/io/fgets), [`fread()`](http://en.cppreference.com/w/c/io/fread), and [`fscanf()`](http://en.cppreference.com/w/c/io/fscanf) library functions, and how you may use them. Then see [this question](http://stackoverflow.com/questions/5431941/while-feof-file-is-always-wrong) why using `feof()` in a while condition is nearly *always* **wrong**. – WhozCraig Oct 29 '13 at 15:49

2 Answers2

0

You need to read from the file in your loop:

char buf[500];

 while ( !feof(pRead) ) {
    fgets(buf, 500, pRead);  // Read another line from the file
    num++ //add one to num
    printf("Num = ",num); //pint the value of num

 } //end loop
Klas Lindbäck
  • 33,105
  • 5
  • 57
  • 82
0

Hello you opened the file but did not read it. Means file pointer stays at the beginning of the file so your loop does not terminate. You can change it to;

char line[100]; //Assuming max. length of one line is 100

while(fgets(line, 100, pRead) != NULL)
{
   //process the read data "line array" here
}
kerberos84
  • 300
  • 1
  • 10