I working on a program that summerizes text documents and I need a way to find the length of the longest and shortest lines in the file and display it in a log file. I've already done a character count and line count. Also say I wanted to created different logfiles for each document i summerize how can this be achieved without overwriting the previos log file?
heres what i've done so far

int main (void)
{
  char fname[128];
  int c, nlines,avgchar=0;
  int charctr= 0;
  FILE *file;

  do{

  printf("Enter the name of a .TXT file:\n");
		gets(fname);

		file=fopen(fname,"r");

		if(file==NULL) 
		{
		printf("Cannot open file.\n");
		return EXIT_FAILURE;

	    }
		else
		{
 
        
	 
	  while ((c = fgetc(file)) != EOF)
	  {

	  	charctr++;
	  	nlines += c == '\n';

	  }
	            avgchar=charctr/nlines;
							
	  											 

			 if((nlines<30)&&(avgchar<60))
			 {
				 printf("Error!!! file cannot be accepted!\n");

              
			 }
			 fclose(file);

			 file=fopen("summaryData.txt","w");
			 fputs("avgchar",file);



	  
		}
  }while((nlines<30)&&(avgchar<60));                                                                           

  
  return 0;
  }

Recommended Answers

All 34 Replies

open the log file for append mode, not write mode, if you want just one log file that contains info for all files
fopen(filename,"a");

or create a unique log file name if you want results in separate log files.

I working on a program that summerizes text documents and I need a way to find the length of the longest and shortest lines in the file and display it in a log file. I've already done a character count and line count.

int main (void)
{
...
    while ((c = fgetc(file)) != EOF)
    {

Instead of fgetc() use fgets() to read an entire line. Then you can add a loop to continue doing the part you have already done, and you can check the length of the line for the min and max.

Or start a counter to count each character and when you read the '\n' test that counter against the current min & max. Then reset the counter to 0 and continue.

I recommend reading the first line and set min & max to the length of that line. That would be a good starting point.

I implemented something like this but the stats are incorrect I want to keep charctr so I can output the average characters perline.

while ((c = fgetc(file)) != EOF)
	  {
		   
					nlines += c == '\n';
	  				charctr++;
	  		
			
					if((charctr='\n')&&(charctr>longest))
					{
						longest=charctr;
					}
					else
						if((charctr='\n')&&(charctr<shortest))
						{
							shortest=charctr;
						}

>>but the stats are incorrect
how do you know that? What are you comparing them to?

the longest line is always ten characters the number of lines is one short and nothing is being written to the log file

does the last line of the file contain '\n' ? If not, then your program will not count it. fgets() will fix that problem because it reads all lines. Getting the length of the longest line is trivel too -- just use strlen() to get the length of the line read by fgets().

The size of the file can not be determined by either your program or using fgets() becuase in MS-Windows os reading text files converts "\r\n" into just "\n". It will be easier to get file length by calling fstat() or stat().

file=fopen("summaryData.txt","w");
			 fputs("avgchar",file);

you forgot to close the file after writing to it. This will cause your program to eventually run out of file handles. And the fputs() statement is probably incorrect -- all it is doing is printing the same hard-coded text "avgchar" in the file each time. Use something like this:

fprintf(file,"%d\n", avgchar);

How do I use fgets if I am not sure of the maximum line size?


while (fgets(line, LINE_MAX, file) != EOF)

Just declare an array of characters. I think 512 should suffice for your purpose.

char buffer[BUFSIZ] = {'\0'} ;
fgets( buffer, BUFSIZ, stdin ) ;
// here BUFSIZ is a macro which is defined as 512
Member Avatar for iamthwee

If you use EOF you will be laughed at. He he. DON'T

I'm trying to use fgets but it isn't proving very easy and of course it doen't complile

/*longest() takes in a file stream and finds the longest line*/
int longest(FILE *file)

{
	char line[BUFSIZE] = {'\0'} ;
	int counter=0;
	int longest=0;//It was suggested that I use -1 but  I don't know why
    while ((fgets( line, BUFSIZE, file )!=EOF))//why shoudn't I use EOF is there something better?	{
	 for (int i=0;i!='\n';++)

	 counter++;

	 if(counter>longest)

	 {
		 longest=counter;
	 }

	}
	return longest; 


}

As far as why not to use EOF is concerned, simple it reads the data from the file one too many times. For detailed explanation, see an excellent tuts by Mr.WaltP and if possible read all of them , they are good.

And btw, where are you opening the file which is passed to the "longest( ) " function. If you are opening it somewhere else then post the entire code.

If you are not opening the "file" stream, then thats what is causing the crash. Before using the file stream you have to open it like:

FILE* fp = NULL ;
fp = fopen( "hello.txt", "r" ) ;

>> while ((fgets( line, BUFSIZE, file )!=EOF))//why shoudn't I use EOF is there something better?

You really should learn to read the documentation about the functions that you use. If you had, you would have found out that fgets() returns a char pointer or NULL when end-of-file is reached. Don't just toss functions at a program without knowning what they do. you can google for most fiunctions, such as "man fgets" will return the man page for that function.

As far as why not to use EOF is concerned, simple it reads the data from the file one too many times. For detailed explanation, see an excellent tuts by Mr.WaltP and if possible read all of them , they are good.

Actually, it's feof() that's the problem. EOF is a good thing to use, it just has to be used with a function that returns it... which fgets() does not...

And btw, where are you opening the file which is passed to the "longest( ) " function. If you are opening it somewhere else then post the entire code.

If you are not opening the "file" stream, then thats what is causing the crash. Before using the file stream you have to open it like:

I am opening the file in main now my value for longest is always zero. I am using separate functions one for the longest and another for the shortest

/*Funtion Prototypes*/

int averagechar(int,int);
int longest(FILE *);

int main(void)
{
  char fname[128];
  int c, nlines,avgchar=0;
  int charctr,max,min= 0;
  FILE *fp;

  

		printf("Enter the name of a .TXT file:\n");
		gets(fname);

		fp=fopen(fname,"r");

		if(fp==NULL) 
			{
			printf("Cannot open file.\n");
			return EXIT_FAILURE;
	
			}
		else
			{
				while ((c = fgetc(fp)) != EOF)
				{

	  			charctr++;/*Chartacter counter*/

	  			nlines += c == '\n';/*Line counter*/

				} 
				
				avgchar=averagechar(charctr,nlines);
				max=longest(fp);
				
			}
		fclose(fp);

			 fp=fopen("summaryData.txt","a");
			 fprintf(fp,"\nAverage Characters=%d\n", avgchar);
			 fprintf(fp,"Length of longest line=%d\n",max);
			 fprintf(fp,"Length of Shortest line=%d\n");
			 fclose(fp);
return 0;
}
/*averagechar() takes in number of lines an line count and returns 
the average number of characters per line*/

int averagechar(int characters,int lines)
{
	int average=0;

	average=characters/lines;

	return average;
}
/*longest() takes in a file stream and finds the longest line*/
int longest(FILE *file)

{
	char line[BUFSIZE] = {'\0'} ;
	int counter=0;
	int longest=0;

    while ((fgets( line, BUFSIZE, file )!=0))
	{
	 
	 counter+=strlen(line);
	}

	 if(counter>longest)

	 {
		 longest=counter;
	 }

	
	return longest; 

}
while ((fgets( line, BUFSIZE, file )!=0))

Please note that " 0 " is not the same as " NULL "

Please note that " 0 " is not the same as " NULL "

Regards Niek

On recent compiler, yes it is. NULL is just a define which is defined as 0

#define NULL 0

on many very old compilers NULL may also be defined as (char*)0.

yes it is

Oops :o
I've checked...You're right, my bad....

my value for longest is always zero

Well that could mean that fgets != 0 is false the first time, so strlen() won't be executed, this way longest would stay 0.
By the way:

while ((fgets( line, BUFSIZE, file )!=0))
{

counter+=strlen(line);
}

Looks to me like this will count the chars in a line, store them in counter, then read the next line and add the number of chars in that line to counter etc. until counter = all chars in file?

until counter = all chars in file?

on MS-Windows os it will not be the same as the file size because it does not include one of the two line terminating character(s). To get the file size add one to counter for each line read except the last line. The last line may or may not contain '\n', so the program has to check the last character to see if it should also account for the '\r' character.

MS-Windows os it will not be the same as the file size

I think you misunderstood me. What I meant was: boujibabe is trying to get the longest sentence, but he/she will get the number of char in the file.
Excuse my crappy English:)

>>Excuse my crappy English, I'm Dutch
Your english is a lot better than my dutch:eek:

btw I'm a she...:o I tried changing the !=0 to NULL, I tried incooperating the if (counter<longest) within the while braces but longest is still returning zilch. So I took out fgets(since I thought it was th e problem) and tried

int longest(FILE *file)
{
	char c;
	int counter=0;
	int longest=0;

	while ((c = fprintf(file,"%c",&c)) != EOF)
	{ 
		if(c !='\n')
		{
			counter=counter+1;
		}
		 if (counter>longest)
			{ 
				longest=counter;
							
			}
	}	
	return longest;	
	}

but unfortunutely this doesn't work either could it be my file pointer since the logic seems correct and none of my other functions using the file pointer is returning anything either?

It probably is. That was what I was getting at in my previous post:

that could mean that fgets != 0 is false the first time

You could try closing the filepointer, then jumping in this function without passing the variable and then reopen the file in the function.

p.s. [off topic]Acient Dragon: I'm signing of for today. Let me be the 1st to congratulate you with y2k posts (allthough you're not there yet at this time)

>> while ((c = fprintf(file,"%c",&c)) != EOF)

Please, stop coding if you know nothing about what you are doing. At least look up the functions before you indiscriminately toss at your program like darts at a dartboard.

>> while ((c = fprintf(file,"%c",&c)) != EOF)

Please, stop coding if you know nothing about what you are doing. At least look up the functions before you indiscriminately toss at your program like darts at a dartboard.

Well I guess I should just toss in my hat and quit then, i'm kinda new at this and I did use the tutorial given as my guide and this what I gathered from it if its wrong then i'm sorry but at least i tried.

Well I guess I should just toss in my hat and quit then,

Nah, no need for that.
What Ancient Dragon is trying to tell you is that you have to look at function-definitions more closely.
What you had before:

while ((fgets( line, BUFSIZE, file )!=0))

should work fine, now just open the file in the int longest function and change the prototype to int longest(void) . Be sure to close the file before you reopen it.

Ok, tried this

int longest(void)

{
	char line[BUFSIZE] = {'\0'} ;
	int counter=0;
	int longest=0;
	char fname[128];
	FILE *file;
	
	file=fopen(fname,"r");
	
	

    while (fgets( line, BUFSIZE, file )!=0)
	{
	 
	 counter=strlen(line);
	

	 if(counter>longest)

		{
		 longest=counter;
		}
   
	}
	return longest; 

}

I'm getting a Debug assertion failed with fgets.c.Seriously, wouldn't it be easier to use something other fgets()? (Just asking don't crucify me)

Actually, it's feof() that's the problem. EOF is a good thing to use, it just has to be used with a function that returns it... which fgets() does not...

Yeah looks like I am desperate need of eyeglasses.

Now back to topic::

Please post your entire code when you update your code.
BTW where have you initialized "fname" variable.

Also if you want to read in entire line from a file, you need to use fgets( ) .

int longest(void)

{
    char line[BUFSIZE] = {'\0'} ;
    int counter=0;
    int longest=0;
    char fname[128];
    FILE *file;
    
    file=fopen( fname,"r" );
    while (fgets( line, BUFSIZE, file )!=0)
    {
// after reading using fgets( ) you need to remove the '\n' at the 
// end of the string or subtract 1 from the strlen( ) result since it will
// always include a '\n'
      counter=strlen(line);
      if(counter>longest)
      {
         longest=counter;
       }
    }
    return longest; 
}

entire code

/*Funtion Prototypes*/

int averagechar(int,int);
int longest(void);
int shortest(void);
int words(FILE *);/*funtions I have written but I won't include them here*/
int sentences(FILE *);

int main(void)
{
  char fname[128];
  int c, nlines,avgchar=0;
  int charctr,max,min,w,sentence= 0;
  FILE *fp;

  

		printf("Enter the name of a .TXT file:\n");
		gets(fname);

		fp=fopen(fname,"r");

		if(fp==NULL) 
			{
			printf("Cannot open file.\n");
			return EXIT_FAILURE;
	
			}
		else
			{
				while ((c = fgetc(fp)) != EOF)
				{

	  			charctr++;/*Chartacter counter*/

	  			nlines += c == '\n';/*Line counter*/

				} 
				fclose(fp);
				
				avgchar=averagechar(charctr,nlines);
				max=longest();
				min=shortest();
				
				
			}
		fclose(fp);

			 fp=fopen("summaryData.txt","a");
			 fprintf(fp,"\nAverage Characters=%d\n", avgchar);
			 printf("\nAverage Characters=%d\n",avgchar);
			 fprintf(fp,"Length of Longest line=%d\n",max);
			 printf("Length of Longest line=%d\n",max);
			 fprintf(fp,"Length of Shortest line=%d\n",min);
			 printf("Length of Shortest line=%d\n",min);
			 
			 fclose(fp);
return 0;
}
/*averagechar() takes in number of lines an line count and returns 
the average number of characters per line*/

int averagechar(int characters,int lines)
{
	int average=0;

	average=characters/lines;

	return average;
}
/*longest() takes in a file stream and finds the longest line*/
int longest(void)

{
	char line[BUFSIZE] = {'\0'} ;
	int counter=0;
	int longest=0;
	char fname[128]={'\0'};
	FILE *file;
	
	file=fopen(fname,"r");
	
	

    while (fgets( line, BUFSIZE, file )!=0)
	{
	 
	 counter=strlen(line)-1;
	

	 if(counter>longest)

		{
		 longest=counter;
		}
   
	}
	return longest; 

}
/*shortest() takes in a file stream and finds the shortest line*/

int shortest(void)

{
	char line[BUFSIZE] = {'\0'} ;
	int counter=0;
	int shortest=0;
	char fname[128]={'\0'};
	FILE *file;
	
	file=fopen(fname,"r");

    while ((fgets( line, BUFSIZE, file )!=0))
	{
	 
	 counter+=strlen(line)-1;
	}

	 if(counter<shortest)

	 {
		 shortest=counter;
	 }

	
	return shortest; 

}

Ok, tried this

int longest(void)

{
	char line[BUFSIZE] = {'\0'} ;
	int counter=0;
	int longest=0;
	char fname[128];
	FILE *file;
	
	file=fopen(fname,"r");
	
	

    while (fgets( line, BUFSIZE, file )!=0)
	{
	 
	 counter=strlen(line);
	

	 if(counter>longest)

		{
		 longest=counter;
		}
   
	}
	return longest; 

}

I'm getting a Debug assertion failed with fgets.c.Seriously, wouldn't it be easier to use something other fgets()? (Just asking don't crucify me)

The debug assertion error fails because the file pointer is NULL, not because fgets() does not work. fname[] is an unitiailzied string which will cause fopen() to return NULL instead of a valid pointer to the FILE object. Your program should check for a vaid fopen() return value.

file=fopen(fname,"r");
                if( file == NULL)
                {
                   // display an error and terminate the program
                 }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.