954,190 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

File operations

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;
  }
boujibabe
Junior Poster
123 posts since Nov 2004
Reputation Points: 10
Solved Threads: 0
 

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.

Ancient Dragon
Retired & Loving It
Team Colleague
30,046 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,342
 

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.

WaltP
Posting Sage w/ dash of thyme
Moderator
10,492 posts since May 2006
Reputation Points: 3,348
Solved Threads: 943
 

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;
						}
boujibabe
Junior Poster
123 posts since Nov 2004
Reputation Points: 10
Solved Threads: 0
 

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

Ancient Dragon
Retired & Loving It
Team Colleague
30,046 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,342
 

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

boujibabe
Junior Poster
123 posts since Nov 2004
Reputation Points: 10
Solved Threads: 0
 

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);
Ancient Dragon
Retired & Loving It
Team Colleague
30,046 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,342
 

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


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

boujibabe
Junior Poster
123 posts since Nov 2004
Reputation Points: 10
Solved Threads: 0
 

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
~s.o.s~
Failure as a human
Administrator
11,938 posts since Jun 2006
Reputation Points: 3,281
Solved Threads: 733
 

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

iamthwee
Posting Expert
5,950 posts since Aug 2005
Reputation Points: 1,543
Solved Threads: 439
 

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; 


}
boujibabe
Junior Poster
123 posts since Nov 2004
Reputation Points: 10
Solved Threads: 0
 

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" ) ;
~s.o.s~
Failure as a human
Administrator
11,938 posts since Jun 2006
Reputation Points: 3,281
Solved Threads: 733
 

>> 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.

Ancient Dragon
Retired & Loving It
Team Colleague
30,046 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,342
 
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...

WaltP
Posting Sage w/ dash of thyme
Moderator
10,492 posts since May 2006
Reputation Points: 3,348
Solved Threads: 943
 

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; 

}
boujibabe
Junior Poster
123 posts since Nov 2004
Reputation Points: 10
Solved Threads: 0
 
while ((fgets( line, BUFSIZE, file )!=0))



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

Nick Evan
Not a Llama
Moderator
10,112 posts since Oct 2006
Reputation Points: 4,142
Solved Threads: 403
 
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.

Ancient Dragon
Retired & Loving It
Team Colleague
30,046 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,342
 
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?

Nick Evan
Not a Llama
Moderator
10,112 posts since Oct 2006
Reputation Points: 4,142
Solved Threads: 403
 
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 tocounter 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.

Ancient Dragon
Retired & Loving It
Team Colleague
30,046 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,342
 
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:)

Nick Evan
Not a Llama
Moderator
10,112 posts since Oct 2006
Reputation Points: 4,142
Solved Threads: 403
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You