Q: Write a program to take C program as input and identify all types of comment line inside
the program. After identifying all types of comment line it’s need to be written back to a
separate file.
CODE:-
#include <stdio.h>
#include <stdlib.h>
void extract_comments(const char *input_file, const char *output_file) {
FILE *infile = fopen(input_file, "r");
FILE *outfile = fopen(output_file, "w");
if (!infile || !outfile) {
printf("Error opening file.\n");
return;
char ch, next_ch;
int in_single_comment = 0, in_multi_comment = 0;
while ((ch = fgetc(infile)) != EOF) {
// Check for single-line comment (//)
if (ch == '/' && (next_ch = fgetc(infile)) == '/') {
in_single_comment = 1;
fputc(ch, outfile);
fputc(next_ch, outfile);
while ((ch = fgetc(infile)) != EOF && ch != '\n') {
fputc(ch, outfile);
}
fputc('\n', outfile);
in_single_comment = 0;
// Check for multi-line comment (/* ... */)
else if (ch == '/' && next_ch == '*') {
in_multi_comment = 1;
fputc(ch, outfile);
fputc(next_ch, outfile);
while ((ch = fgetc(infile)) != EOF) {
fputc(ch, outfile);
if (ch == '*' && (next_ch = fgetc(infile)) == '/') {
fputc(next_ch, outfile);
fputc('\n', outfile);
in_multi_comment = 0;
break;
fclose(infile);
fclose(outfile);
int main() {
char input_file[100], output_file[100];
printf("Enter the name of the input C file: ");
scanf("%s", input_file);
printf("Enter the name of the output file: ");
scanf("%s", output_file);
extract_comments(input_file, output_file);
printf("Comments extracted successfully to %s\n", output_file);
return 0;
OUTPUTUT: