Thread: reading characters in a file

  1. #1
    Registered User
    Join Date
    Mar 2003
    Posts
    1

    reading characters in a file

    Hi

    I have written the following code to count the number of lines in a file however I want to change this so I can find out how many words there are in the file and how many characters there are. Can anyone please help, thank you


    #include <stdio.h>

    /*Function Prototype*/
    int nlines(char name[]);

    void main(void)
    {
    char fname[100];
    int lines;

    printf("Program countlines lists the number of lines in a file.\n\n");

    printf("Enter the file name: ");
    scanf("%99s",fname);

    lines=nlines(fname);

    printf("There are %d lines in file %s",lines,fname);
    }

    /*Function Definition*/
    int nlines(char name[])
    {

    FILE *ipfile;
    char ch;
    int nlines=0;

    ipfile=fopen(name,"r");

    if (ipfile==NULL)
    {
    printf("Error opening file \"%s\".",name);
    }
    else
    {
    do
    {
    ch=fgetc(ipfile);
    if (ch!=EOF)
    {
    if(ch=='\n')
    {
    nlines+=1;
    }
    }
    }
    while (ch!=EOF);
    fclose(ipfile);

    nlines+=1;

    }

    return nlines;
    }

  2. #2
    Registered User Vber's Avatar
    Join Date
    Nov 2002
    Posts
    807
    Read this and edit your post.

  3. #3
    Registered User Dev's Avatar
    Join Date
    Mar 2003
    Posts
    59
    Read the book ' The C Programming language ' by the autor of the language.

    That book has all sort of such programs and many more at advanced level too.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Post...
    By maxorator in forum C++ Programming
    Replies: 12
    Last Post: 10-11-2005, 08:39 AM
  2. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  3. Simple File encryption
    By caroundw5h in forum C Programming
    Replies: 2
    Last Post: 10-13-2004, 10:51 PM
  4. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM
  5. what does this mean to you?
    By pkananen in forum C++ Programming
    Replies: 8
    Last Post: 02-04-2002, 03:58 PM