I found this problem of yours harder than expected. Firstly, I'm better at C++ libraries than the C libraries. So I had to revise all my C File I/O. Secondly, I hate parsing. Anyway here's my solution to your problem.
My technique isn't perfect.
It removes all C-style comments. (/* */) but if it encounters the comments in a string (which is rare in real practical life), it will ignore anything between them in the string.
Plus, I have little experience in parsing text files, so the way I did it may seem messy.
I have posted the code below. The code in HTML format can be viewed here if you prefer syntax highlighting.
/*
+-----------------------------------------------------------------+
| Author: Lim Chong Liang, Andrew |
| Filename: comment.cpp |
| Description: This program takes a C source file, and copies the |
| text into a new .txt file, with all the comments |
| removed. The program only removes C-style |
| comments and by default copies itself. |
| Copyright: Lim Chong Liang, Andrew, 2003 |
| Website: http://www.abdn.ac.uk/~u02cll2/ |
| Email: demandred90@hotmail.com OR u02cll2@abdn.ac.uk |
+-----------------------------------------------------------------+
*/
#include <stdio.h>
#include <stdlib.h>
void copyFileWithoutComments(char[], char[]) ;
/*
* The main function.
*/
int main(int argc, char *argv[])
{
char fileToRead[] = "comment.c" ;
char fileToWrite[] = "comment.txt" ;
copyFileWithoutComments(fileToRead,fileToWrite) ;
printf("'%s' has been copied to '%s', with all C-style comments removed.\n",
fileToRead, fileToWrite) ;
system("PAUSE");
return 0;
}
/*
* Copies a C source file to a new text file, with all C-style comments removed.
* fileToRead - The name of the C source file.
* fileToWrite - The name of the new text file.
*/
void copyFileWithoutComments(char fileToRead[], char fileToWrite[])
{
FILE * fRead ;
FILE * fWrite ;
/* buffer for a line */
char lineBuffer[256] ;
/* open file for reading */
fRead = fopen(fileToRead,"r");
/* stop reading if file pointer is NULL */
if (fRead == NULL)
{
printf("Could not open file for reading.") ;
return ;
}
/* open file for writing */
fWrite = fopen(fileToWrite,"w") ;
if (fWrite == NULL)
{
printf("Could not create file for writing.") ;
return ;
}
/* holds character read */
char next ;
/* to check if currently in a comment */
int inComment = 0 ;
/* keep reading until end of file */
while ( (next = fgetc(fRead)) != EOF )
{
/* We are NOT within a comment. */
if ( !inComment )
{
if ( next == '/' ) {
char temp = fgetc(fRead) ;
if ( temp == '*' )
inComment = 1 ;
else {
fputc(next,fWrite) ;
fputc(temp,fWrite) ;
}
}
else
fputc(next,fWrite) ;
}
/* We are in a comment. */
else
{
if ( next == '*' ) {
char temp = fgetc(fRead) ;
if ( temp == '/' )
inComment = 0 ;
}
}
}
/* close files */
fclose(fWrite) ;
fclose(fRead) ;
}