473,397 Members | 2,068 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,397 software developers and data experts.

Code review

Hi,
This code finds the number of non-commented lines in a given source
file.
Works fine except for one condition that i found.
If the Input file is of the below kind :
#include<xyz.h>/* declare headers
declare main*/int main()
{
return 0;
}
/* Input file ends here */

Result:
actual output should be : Number of non-commented lines is 5
Output from code I got is : Number of non-commented lines is 4 !

Can anyone of you point the mistake or better way of going about.
- Ravi
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

/* Maximum chars in any line. If this is crossed then the remaining
bytes are ignored */
#define BYTES 512

/* line is valid if it contains any of the following chars. Otherwise
treated as commented */
#define VALID_CHARS "\\abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTU VWXYZ;,'/#{}()*+-0123456789"

int comment_handler ( FILE *fptr, char *c)
{
int ind = 0;
char ch;

if ( ( ch = fgetc ( fptr )) =='*')/* checks for '/*' */
{
while ( !ind )
{
if (fgetc ( fptr ) == '*' )
{
if ( fgetc ( fptr ) == '/')/* checks for end of comment */
{
ind = 1;
*c = fgetc ( fptr);
}
}
}
}
else if ( ch == '/')/* checks cpp comment */
{
while ( (!feof (fptr) ) && ( ch != '\n'))/* end of line check for \n
*/
ch = fgetc ( fptr );

*c = ch;
}
else/* Special case: No comments found */
{
*c = ch;/* Storing next character */
return 0;/* The char is single '/' */
}

return 1;
}

int main (int argc, char *argv[])
{
int i = 0, j = 0, flag = 0;
char ch = 0;
char buffer[BYTES];/* variable holds a max of BYTES (defined) chars in
any line */
FILE *fp = NULL, *fout = NULL;

if ( argc < 3 ) return EXIT_FAILURE;

fp = fopen ( argv[1], "r+b");/* open the source file */

if ( fp == NULL ) return EXIT_FAILURE;

fflush ( stdout);
fout = fopen ( argv[2], "w+b");/* open the output file */

if ( fout == NULL ) return EXIT_FAILURE;

while ( (!feof (fp )) && (!ferror (fp) ))
{
memset ( buffer, 0x00, BYTES);
while ( (j != BYTES-1) && (!flag) )/* Check for max BYTES-1 chars */
{
ch = fgetc ( fp );

if ( ch == '/')
if (comment_handler ( fp, &ch ) == 0)
buffer[j++] = '/';

if ( (ch == '\n') || (feof (fp)))
flag = 1;

/* dont add '\n' or '\r' to the running buffer cause its appended in
the fprintf */
if ( ( ch !='\n' ) && ( ch != '\r'))
buffer[j++] = ch;
}
if (j == BYTES-1)/* line has more than BYTES chars, so ignore them !
*/
{
j++;
while ( (!feof (fp )) && (!ferror (fp) ))
{
ch = fgetc(fp);
if ( ch == '\n')
break;
}
}

if (strpbrk (buffer, VALID_CHARS))
{
fprintf ( fout, "%s\n", buffer);
i++;
}

j = flag = ch = 0;
}
printf ("\n*** Number of non commented lines is : %d ***\n\n", i);

fclose ( fp );
fclose ( fout );
return EXIT_SUCCESS;
}
Nov 13 '05 #1
4 1963
On 24 Jul 2003 22:05:40 -0700,
Ravi Uday <ra*****@yahoo.com> wrote:
Hi,
This code finds the number of non-commented lines in a given source
file.
Works fine except for one condition that i found.
It also fails when there is a 'comment' inside of a string:

char *some_string = "A string /* with a comment */";
Can anyone of you point the mistake or better way of going about.
Use a state machine, and parse character by character, so that at all
times you know whether you're in a comment or not, and whether you're
in a string or not.

A few remarks:
/* Maximum chars in any line. If this is crossed then the remaining
bytes are ignored */
#define BYTES 512
You should at least put out a warning when you ignore that sort of
thing.
if ( ( ch = fgetc ( fptr )) =='*')/* checks for '/*' */
This is an illegal comment.
if ( argc < 3 ) return EXIT_FAILURE;
You should print out a usage statement. Especially if you expect
people to try your code.
fp = fopen ( argv[1], "r+b");/* open the source file */
You keep talking about "lines" but here you open the file in binary
mode. And why do you open it for update?
if ( fp == NULL ) return EXIT_FAILURE;
You should print an error message.
fflush ( stdout);
Why?
fout = fopen ( argv[2], "w+b");/* open the output file */
Again, why open for update, when you intend to just write?
while ( (!feof (fp )) && (!ferror (fp) ))


You should read the C FAQ (http://www.eskimo.com/~scs/C-faq/top.html),
question 12.2. This is not the right way to read from a file.

[snip of very convoluted loop block]
Martien
--
|
Martien Verbruggen | If it isn't broken, it doesn't have enough
Trading Post Australia | features yet.
|
Nov 13 '05 #2
>Hi,
This code finds the number of non-commented lines in a given source
file.
Works fine except for one condition that i found.
If the Input file is of the below kind :
#include<xyz.h>/* declare headers GOT COMMENT
declare main*/int main() GOT COMMENT
{ NOT GOT COMMENT 1
return 0; NOT GOT COMMENT 2
} NOT GOT COMMENT 3
/* Input file ends here */ GOT COMMENT (if this line was even included at all)

Result:
actual output should be : Number of non-commented lines is 5
Output from code I got is : Number of non-commented lines is 4 !


I don't agree with your correct answer.
I claim the correct number of non-commented lines is 3.

Perhaps you would care to define "non-commented line" and explain
how you got the so-called "correct answer"?

"a non-commented line is a line that has no part of a comment in it".

Gordon L. Burditt
Nov 13 '05 #3
Ravi Uday wrote:

[ deleted ]

Use a state machine, and parse character by character, so that at all
times you know whether you're in a comment or not, and whether you're
in a string or not.


Any sites which mention of State machines and ways of doing that ?
As for comment in a string i shall write another function which makes sure
that if a * " * is found then parse till it finds another * " * and treat it
as a non-commented line.


http://www.jfar.org/article001.html
--
Julian V. Noble
Professor Emeritus of Physics
jv*@lessspamformother.virginia.edu
^^^^^^^^^^^^^^^^^^
http://galileo.phys.virginia.edu/~jvn/

"Science knows only one commandment: contribute to science."
-- Bertolt Brecht, "Galileo".
Nov 13 '05 #4
In article <3F***************@virginia.edu>, jv*@virginia.edu says...
http://www.jfar.org/article001.html


Is this comp.lang.forth? :-)
Nov 13 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Arvie | last post by:
I need some advice guys.. I am proposing that we get someone to do a complete audit/review of our Java application codebase, about 1000 JSPs/Servlets and 100 EJBs. If I get firms to submit...
0
by: gs-code-review-bounces | last post by:
Your mail to 'gs-code-review' with the subject Re: Application Is being held until the list moderator can review it for approval. The reason it is being held: Post by non-member to a...
18
by: Ben Hanson | last post by:
I have created an open source Notepad program for Windows in C++ that allows search and replace using regular expressions (and a few other extras). It is located at...
19
by: Swaregirl | last post by:
Hello, I would like to build a website using ASP.NET. I would like website visitors to be able to download code that I would like to make available to them and that would be residing on my...
3
by: Filippo | last post by:
Hi, In my organization we would like to activate a code review system, in wich a developer have to pass a review from a reviewer before check in the modified files in source safe. Is there any way...
239
by: Eigenvector | last post by:
My question is more generic, but it involves what I consider ANSI standard C and portability. I happen to be a system admin for multiple platforms and as such a lot of the applications that my...
3
by: JeanDean | last post by:
I am looking for freeware tool which can review the c++ code(compiled on g++). Please share your experiences and details obout the usage of the tool.
10
by: Jo | last post by:
Hi there: I m wondering what can I do to improve my code, everytime I am coding I feel like it could be done better. I started on c# a good months ago and feel conformtable but sometimes I Need...
4
maxx233
by: maxx233 | last post by:
Hello all, I'm new to OO design and have a question regarding where I should place some code. Here's a simplified situation: I'm making an app to do create, submit, and track employee reviews...
0
by: corey | last post by:
Secure Bytes audit and vulnerability assessment software Secure Auditor named “Versatile tool” and earn “Five Star Ratings” in SC Magazine Group Test Secure Bytes is really pleased to share this...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.