Thread: C program character count

  1. #1
    Registered User
    Join Date
    Dec 2016
    Posts
    96

    C program character count

    Good day!

    I am trying to build a C program for a character count, but it does not work for some reason. Can someone please tell me why?

    character count:
    Code:
    #include <stdio.h>        /* Standard IN/OUT library. */
    #include <stdint.h>        /* Standard extended....... library. */
    /* #include <io.h> */         /* This library is not present in this compiler. */
    #include <stdlib.h>
    #include <conio.h>
    #include <string.h>
    #include <math.h>
    
    char *CharacterCount (char *InputFilename, char *ReturnedString)
    {
                        // Local variables.
      int i, n, b, t, iAll;
      char sAll[5], sBlanks[5], sTabs[5], sNewLines[5];
      //char sC[5];
      char c;
      //char sStr[100];
      FILE *ifp;
      char *InMode = "r";
    
      ifp = fopen(InputFilename, InMode);
    
      if (ifp == NULL)
      {
                return "-1";
                                                                            /* MS DOS. */
                //fprintf(stderr, "Can't open input file %s!\n", InputFilename);
                exit(-1);                                   /* Maybe should be "1". */
      }
    
      for (i=0, n=0, b=0, t=0, iAll=0; ; i++)                       /* The use of "while" will lead to wrong reading of the characters(44141242145), */
      {                                                                /* probably counts the addresses not the characters. */
        c = fgetc(ifp);                                                /* Automatic incrementation, after every read the counter is set to the next element. */
        if (c == EOF)
            break;
        if (c == '\n')
            n++;
        if (c == ' ')
            b++;
        if (c == '\t')
            t++;
        iAll++;
      }
    
      fclose(ifp);                                                  /* All files must be closed. */
    
    
                                                                    /* Convert int iAll to string sAll. */
        itoa (i, sAll, 10);
                                                                    /* Convert int c to string sC. */
        //itoa(*c, sC, 10);
                                                                    /* Convert int Blanks to string sBlanks. */
        itoa(b, sBlanks, 10);
                                                                    /* Convert int Tabs to string sTabs. */
        itoa(t, sTabs, 10);
                                                                    /* Convert int NewLines to string sNewLines. */
        itoa(n, sNewLines, 10);
                                                                    /* Convert all the text and char variables into 1 string. */
        sprintf(&ReturnedString [0], "All == %s,\nCharacters == %s,\nBlanks == %s,\nTabs == %s,\nNewlines == %s.", sAll, sBlanks, sTabs, sNewLines);
        /* This is the only way that works, on the forums they say its not safe. */
    
      return "0";
    }
    Last edited by Salem; 03-08-2020 at 12:24 AM. Reason: long lines folded

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    What's your definition of "doesn't work"?

    Doesn't compile?
    Compiles but crashes before it does anything
    Runs without crashing, but produces no output.
    Produces output, but the output is garbage.
    Produces output, but the output is predictably wrong.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Dec 2016
    Posts
    96
    C program character count-codeblocks_2-png

  4. #4
    Registered User
    Join Date
    Mar 2020
    Posts
    2
    Quote Originally Posted by ArakelTheDragon View Post
    Code:
      return "0";
    You return the literal string "0". So if you're printing out what the functions returns of course you're going to get "0". You probably want to return a pointer to the string you just wrote:

    Code:
      return ReturnedString;

  5. #5
    Registered User Sir Galahad's Avatar
    Join Date
    Nov 2016
    Location
    The Round Table
    Posts
    277
    Quote Originally Posted by ArakelTheDragon View Post
    Good day!

    I am trying to build a C program for a character count, but it does not work for some reason. Can someone please tell me why?

    character count:
    Code:
    #include <stdio.h>        /* Standard IN/OUT library. */
    #include <stdint.h>        /* Standard extended....... library. */
    /* #include <io.h> */         /* This library is not present in this compiler. */
    #include <stdlib.h>
    #include <conio.h>
    #include <string.h>
    #include <math.h>
    
    char *CharacterCount (char *InputFilename, char *ReturnedString)
    {
                        // Local variables.
      int i, n, b, t, iAll;
      char sAll[5], sBlanks[5], sTabs[5], sNewLines[5];
      //char sC[5];
      char c;
      //char sStr[100];
      FILE *ifp;
      char *InMode = "r";
    
      ifp = fopen(InputFilename, InMode);
    
      if (ifp == NULL)
      {
                return "-1";
                                                                            /* MS DOS. */
                //fprintf(stderr, "Can't open input file %s!\n", InputFilename);
                exit(-1);                                   /* Maybe should be "1". */
      }
    
      for (i=0, n=0, b=0, t=0, iAll=0; ; i++)                       /* The use of "while" will lead to wrong reading of the characters(44141242145), */
      {                                                                /* probably counts the addresses not the characters. */
        c = fgetc(ifp);                                                /* Automatic incrementation, after every read the counter is set to the next element. */
        if (c == EOF)
            break;
        if (c == '\n')
            n++;
        if (c == ' ')
            b++;
        if (c == '\t')
            t++;
        iAll++;
      }
    
      fclose(ifp);                                                  /* All files must be closed. */
    
    
                                                                    /* Convert int iAll to string sAll. */
        itoa (i, sAll, 10);
                                                                    /* Convert int c to string sC. */
        //itoa(*c, sC, 10);
                                                                    /* Convert int Blanks to string sBlanks. */
        itoa(b, sBlanks, 10);
                                                                    /* Convert int Tabs to string sTabs. */
        itoa(t, sTabs, 10);
                                                                    /* Convert int NewLines to string sNewLines. */
        itoa(n, sNewLines, 10);
                                                                    /* Convert all the text and char variables into 1 string. */
        sprintf(&ReturnedString [0], "All == %s,\nCharacters == %s,\nBlanks == %s,\nTabs == %s,\nNewlines == %s.", sAll, sBlanks, sTabs, sNewLines);
        /* This is the only way that works, on the forums they say its not safe. */
    
      return "0";
    }
    You really need to learn to "separate concerns" in the organization of your code. Think of it like a machine. The more self-contained parts, the easier it is to write virtually bug-free code. So make a function that just counts ASCII. The function that returns the string in your example should probably be eliminated. Too specific, you might as well just put that code into main().

    Another major problem is your failure to verify lengths before writing to strings. This is a very dangerous habit! Buffer overflows are like the #1 problem when it comes to system security. Always make a point of checking your code for these kinds of issues. You can calculate the exact number of bytes needed to represent any integer using a bit of maths, but the simplest thing to do is just pick some number that is guaranteed to be long enough. A choice of 32 bytes for example would cover all the integers up to 64-bits long.

    One more thing, since you're working with ASCII you can make things more efficient using a lookup table.

    Code:
    #include <stdio.h>
    #include <string.h>
    
    void count_ascii(char* text, size_t counts[256])
    {
     memset(counts, 0, sizeof(size_t) * 256);
     while(*text)
      ++counts[*text++];
    }
    
    /* Not thread-safe! */
    size_t* count_ascii_static(char* text)
    {
     static size_t counts[256];
     count_ascii(text, counts);
     return counts;
    }
    
    int main(int argc, char** argv)
    {
     puts("- Count Ascii -");
     printf("Usage: %s [TEXT]\n", *argv);
     while(*(++argv))
     {
      char* text = *argv;
      printf("\"%s\"\n", text);
      size_t* counts = count_ascii_static(text);
      for(size_t index = 0; index < 256; ++index)
       if(counts[index])
        printf("%c (%ld): %ld\n", (char)index, index, counts[index]);
     }
    }

  6. #6
    Registered User
    Join Date
    Jun 2019
    Posts
    44
    This may not be what you're looking for but strlen works well.


    Code:
    #include <string.h> 
    #include <stdlib.h> 
    #include <stdio.h> 
    
    #define BUFFER_1024 1024
    
    
    int main() {
    
    FILE *fptr, *fptw;
    
    
         fptr=fopen("file/A.txt","r");
         fptw=fopen("file/B.txt","w");
    
    
        int len;
        char array[20]="myfile or mystring";
    
    
        len = strlen(array) ;
    
    
        printf ( "FileSize: %d\n" , len ) ;
        
        fclose(fptr);
        fclose(fptw);
    
    
         return 0;
    }

  7. #7
    Registered User
    Join Date
    Dec 2016
    Posts
    96
    No matter how I do it, it does not work. I even did it with DOS, it does not work .

    main code:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <dos.h>
    #include <windows.h>
    #include <windowsx.h>
    #include <mmsystem.h>
    #include <ctype.h>                          // getint ().
    #include <conio.h>                          // getch (), ungetch ().
    #include "Y:/Other/Library_OS/Functions.h"  // List of the functions.
    
    
                                                /* Definitions. */
    #define SIZE 255
    
                                                /* Function declarations. */
    
    int main()
    {
        /* Local variables and initialization. */
        int a = 0;                              // Used to select which function should be activated.
        int TemporaryVariable = 0;              // Used in all functions.
        char TemporaryString [256] = "Y:\\Other\\OS.cmd.Toolbox\\Testing.c";
        //TemporaryString [35] = '\0';
    
    
        while (1)
        {
            printf ("Enter operation: \n");
            printf ("1. Encryption.\n");
            printf ("2. CharacterCount.\n");
            printf ("3. ")
             scanf("%i", &a);                             /*The scanf function  takes the address of a variable to put the result into.
                                                         Writing scanf("%d", &someVar) will pass the address of the someVar  variable (using the & unary operator). */
    
            switch (a)
            {
                case 1: Encryptmain ();
                    break;
                case 2:
                    TemporaryVariable = CharacterCount(TemporaryString);
                    if (TemporaryVariable != -1)
                        printf ("Characters = %d\n", TemporaryVariable);
                    else printf ("Can't open the file.\n");
                    break;
                default: printf ("Operation or numbers are not supported.\n");
                    break;
            }
    
    
        }
    
        return 0;
    }
                                                /**** Core functions. ****/
    Function code:
    Code:
    #include "Y:/Other/Library_OS/Functions.h"
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <ctype.h>
    
    /***********************************************  Character count  ********************************************************************************/
    int CharacterCount (char *InputFilename)
    {
                        // Local variables.
      unsigned int i = 0;                         // Counter.
      char c;                                     // Used to read 1 character at a time with fgetc ().
      int AlphaNumeric = 0;                       // Will store the alphanumeric characters' amount.
      //char ItoaBuffer;                            // Used in itoa () to convert int to string.
      FILE *fp;
      char *InMode = "r";
    
      fp = fopen(InputFilename, InMode);
    
      if (fp == NULL)
      {
          return -1;
      }
    
      else {
        printf ("DEBUG: ");
        AlphaNumeric = strlen(fp);
    
      fclose(fp);                                 /* All files must be closed. */
    
         //itoa (AlphaNumeric, ReturnedString,  10);                                                   /* Convert all  the text and char variables into 1 string. */
         //sprintf(&ReturnedString [0], "All == %s,\nCharacters ==  %s,\nBlanks == %s,\nTabs == %s,\nNewlines == %s.", sAll, sBlanks, sTabs,  sNewLines);                    /* This is the only way that works, on  the forums they say its not safe. */
    
      return AlphaNumeric;
        }
    }

  8. #8
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    strlen is used to count the length of a null terminated string. You passed it a file pointer, so of course it doesn't work.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  9. #9
    Registered User
    Join Date
    Dec 2016
    Posts
    96
    Like this the program bugs and freezes like its processing something, the cmd flashes the dash but no result is ever given:

    Code:
        while (fgetc (fp) != feof (fp))
            AlphaNumeric++;

  10. #10
    Registered User
    Join Date
    Mar 2020
    Posts
    2
    fgetc returns a character or EOF. feof returns 0 if not at end of file or a non-zero value if it has been reached. I don't understand how you got the idea to compare the two. The correct code would look like:

    Code:
        while(fgetc(fp) != EOF)
             AlphaNumeric++; /* Not alphanumeric only, counts all bytes. */

  11. #11
    Registered User
    Join Date
    Dec 2016
    Posts
    96
    Quote Originally Posted by vlads View Post
    fgetc returns a character or EOF. feof returns 0 if not at end of file or a non-zero value if it has been reached. I don't understand how you got the idea to compare the two. The correct code would look like:

    Code:
        while(fgetc(fp) != EOF)
             AlphaNumeric++; /* Not alphanumeric only, counts all bytes. */
    I tried it like this a million times, but it did not work, now for some unknown reason it works .

    But now when I compare for a blank, tab and newline it does not increment.

    Code:
    int CharacterCount (char *InputFilename, unsigned int *Blanks, unsigned int *Tabs, unsigned int *Newlines)
    {
                        // Local variables.
      unsigned int i = 0;                         // Counter.
      char c;                                     // Used to read 1 character at a time with fgetc ().
      int AlphaNumeric = 0;                       // Will store the alphanumeric characters' amount.
      //char ItoaBuffer;                            // Used in itoa () to convert int to string.
      FILE *fp;
      char *InMode = "r";
    
      //printf ("DEBUG: %s\n", InputFilename);
      fp = fopen(InputFilename, InMode);
    
      if (fp == NULL)
      {
          return -1;
      }
    
      else {
        printf ("DEBUG: ");
        for (i=0; c = fgetc(fp) != EOF; i++)
        {
    
            AlphaNumeric++; /* Not alphanumeric only, counts all bytes. */
            if (c == ' ')
                *Blanks++;
            if (c == '\t')
                *Tabs++;
            if (c == '\n')
                *Newlines++;
        }
    
      fclose(fp);                                 /* All files must be closed. */
    
        //itoa (AlphaNumeric, ReturnedString, 10);                                                   /* Convert all the text and char variables into 1 string. */
        //sprintf(&ReturnedString [0], "All == %s,\nCharacters == %s,\nBlanks == %s,\nTabs == %s,\nNewlines == %s.", sAll, sBlanks, sTabs, sNewLines);                    /* This is the only way that works, on the forums they say its not safe. */
    
      return AlphaNumeric;
        }
    }

  12. #12
    Registered User
    Join Date
    May 2009
    Posts
    4,183
    I have no idea if this will help; but, I will add () to see if it works.

    Code:
    for (i=0; c = fgetc(fp) != EOF; i++)
    Code:
    for (i=0; (c = fgetc(fp)) != EOF; i++)
    Tim S.
    "...a computer is a stupid machine with the ability to do incredibly smart things, while computer programmers are smart people with the ability to do incredibly stupid things. They are,in short, a perfect match.." Bill Bryson

  13. #13
    Registered User
    Join Date
    Dec 2016
    Posts
    96
    Quote Originally Posted by stahta01 View Post
    I have no idea if this will help; but, I will add () to see if it works.

    Code:
    for (i=0; c = fgetc(fp) != EOF; i++)
    Code:
    for (i=0; (c = fgetc(fp)) != EOF; i++)
    Tim S.
    I already though of this and tried this, but it does not work. I think it might be Windows 10 which does not have a real DOS OS and is made to not work with C.

  14. #14
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by ArakelTheDragon
    I already though of this and tried this, but it does not work.
    You should make the change anyway because this is wrong:
    Code:
    c = fgetc(fp) != EOF;
    the above is equivalent to:
    Code:
    c = (fgetc(fp) != EOF);
    which means that instead of being the return value of fgetc, c is always either 0 or 1. Hence, the parentheses for grouping is required.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  15. #15
    Registered User
    Join Date
    May 2009
    Posts
    4,183
    Is there any reason you have an "*" in front of this?

    Code:
    *Blanks++;
    Edit: I see the reason now; but, you are likely calling CharacterCount wrong.

    Tim S.
    "...a computer is a stupid machine with the ability to do incredibly smart things, while computer programmers are smart people with the ability to do incredibly stupid things. They are,in short, a perfect match.." Bill Bryson

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. count and print the frequency of each ASCII character
    By s_jsstevens in forum C Programming
    Replies: 3
    Last Post: 02-07-2011, 09:33 PM
  2. Character count program
    By tiger6425 in forum C Programming
    Replies: 3
    Last Post: 09-04-2010, 01:35 PM
  3. simple program to count the character not working
    By hitesh1511 in forum C Programming
    Replies: 12
    Last Post: 08-08-2006, 04:13 AM
  4. Again Character Count, Word Count and String Search
    By client in forum C Programming
    Replies: 2
    Last Post: 05-09-2002, 11:40 AM

Tags for this Thread