0% found this document useful (0 votes)
12 views4 pages

Assignment 3

The provided C program reads a C source file and extracts all types of comments, including single-line (//) and multi-line (/* ... */) comments. It writes the extracted comments to a specified output file. The program handles file operations and user input for file names.

Uploaded by

Nehal Srivastava
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views4 pages

Assignment 3

The provided C program reads a C source file and extracts all types of comments, including single-line (//) and multi-line (/* ... */) comments. It writes the extracted comments to a specified output file. The program handles file operations and user input for file names.

Uploaded by

Nehal Srivastava
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

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:

You might also like