-2

I need to write a C script with which I should be able to count all letters on each line in a text file and print each value. The text file has to be a parameter given when running the C script.

#include <stdio.h>
#include <string.h>
int main(int argc,char * argv[])
{
    char *g, linie[1000];
    int nrChar=0;
    FILE *f=fopen(argv[1],"r");
    g=fgets(linie,1000,f);
    while(g!=NULL)
    {
    nrChar=strlen(linie)-2;
    printf("cuv is %d\n",nrChar);
        g++;
        g=fgets(linie,1000,f);     
    }   

    fclose(f);
    return 0;
}

This is what I tried, but it doesn't work.

I am expecting something like:

2
3
5
4
1

Supposing I have a .txt file which contains:

do
abc
linux
bash
c
Sebi CN
  • 51
  • 9

1 Answers1

0

You have several problems:

  1. You aren't printing the value returned by strlen which is what you want to do.
  2. fgets leaves the trailing newline, if it exists, in the string. So you need to remove it.
  3. Your lines g++, and max=1 don't do anything. Remove them.
  4. Check whether fopen succeeded before operating on the file.
  5. Check if the user passed a filename argument on the command line (ie: argc >= 2 before attempting to reference argv[1].
  6. You compute the maximum length of all the words in your maxChar variable, but then you print 'nrChar` which is the length of the last word found.

This code compiles with no warnings using gcc -Wall -Wextra and gives the expected output:

#include <stdio.h>
#include <string.h>
int main(int argc,char * argv[])
{
    char *g,*p,linie[1000];
    int maxChar=0, nrChar=0;
    if (argc < 2)
    {
        fprintf(stderr, "Usage: %s <filename>\n", argv[0]);
        return 0;
    }
    FILE *f=fopen(argv[1],"r");
    if (f == NULL)
    {
        fprintf(stderr, "Error: Could not open %s for read!\n", argv[1]);
        return 0;
    }
    g=fgets(linie,1000,f);
    while(g!=NULL)
    {
        p = strchr(linie, '\n');  //fgets leaves the '\n' in the buffer
        if (p != NULL) *p = 0;    //find the '\n' and replace with 0

        nrChar = strlen(linie);
        printf("%d\n", nrChar);   //need to print the value from strlen
        if(maxChar<nrChar)
        {
            maxChar = nrChar;
        }
        g=fgets(linie,1000,f);
    }
    printf("The longest word has %d letters \n",maxChar);

    fclose(f);
    return 0;
}
MFisherKDX
  • 2,840
  • 3
  • 14
  • 25
  • Yes, i just realized i did some rookie mistakes, caused by the lack of knowledge in working in C. Your solution worked as expected and was pretty clear how it works. Thanks a mili! – Sebi CN Apr 02 '19 at 20:32