reading characters in a file

This is a discussion on reading characters in a file within the C Programming forums, part of the General Programming Boards category; Hi I have written the following code to count the number of lines in a file however I want to ...

  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
    Dev
    Dev is offline
    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, 09:39 AM
  2. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 07:39 AM
  3. Simple File encryption
    By caroundw5h in forum C Programming
    Replies: 2
    Last Post: 10-13-2004, 11:51 PM
  4. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 10: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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21