Welcome to Dream.In.Code
Become a C++ Expert!

Join 149,931 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 1,751 people online right now. Registration is fast and FREE... Join Now!




How to count total file?

 
Reply to this topicStart new topic

How to count total file?

dudutz_ne
6 Jan, 2008 - 04:28 PM
Post #1

New D.I.C Head
*

Joined: 26 Sep, 2007
Posts: 2


My Contributions
CODE
FILE *open;

      int total=1;
      open=fopen("input.txt","r");
         while(!feof(open))
             {
                    total++;
            };
         printf("%d",total);
         getch();
      fclose(open);


I have a problem to count how many file inside the input.txt file... but the output won't appear...

File inside input.txt

23
45
13
24
40


I need to make the amount of "total" equal to 5, it'll change depend on how many file inside the input.txt list... I hope I make myself clear... thanks everyone for your help...

User is offlineProfile CardPM
+Quote Post

Martyr2
RE: How To Count Total File?
6 Jan, 2008 - 04:53 PM
Post #2

Programming Theoretician
Group Icon

Joined: 18 Apr, 2007
Posts: 5,655



Thanked: 313 times
Expert In: C/C++, Java, VB, VB.NET, C#, PHP, Web Development, HTML & CSS, Javascript

My Contributions
You were close but you had a few problems. One you shouldn't put a semicolon after the while loop. The second is that you should read in data from the file so that it advances the internal pointer of the file.

Here is a copy of your program with modifications to give you the number of lines assuming that each line of the file is less than 100 characters long.

CODE

#include <iostream>
#include <conio.h>
using namespace std;

int main() {
    FILE *open;

    // Temporarily hold a string of the file (100 chars)
    char temp[100];

    // Set total = 0, not 1. Makes no sense.
    int total=0;

    open = fopen("input.txt","r");
    while(!feof(open))
    {
        // Missing part, read in data and count
        // NOTE: Don't put a semicolon after the while loop
        fgets(temp,100,open);
        total++;
    }

    // Print the total
    printf("%d",total);
    fclose(open);

    getch();
    return 0;
}


I have put some in code comments to show you what I am doing and where I am putting the changes. This should help you out.

Enjoy!

"At DIC we be file reading code ninjas with attitude!" decap.gif

This post has been edited by Martyr2: 6 Jan, 2008 - 04:54 PM
User is offlineProfile CardPM
+Quote Post

Reply to this topicStart new topic
Time is now: 1/8/09 03:24PM

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter

Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month