Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

In this project, you have been asked to write a program that after execution it

ID: 3810008 • Letter: I

Question

In this project, you have been asked to write a program that after execution it does the following: (PROGRAM IN C ONLY)

1-Read its own source file

2-Create another text file which is the same as its source file but the text file has line number. An example of running this program on the different source file (the assignment for computation of Body Mass Index) leads to generation of a file as

001: #include

002:

003: int main(void)

004: {

005: float mass, height;

006: float BMI;

007:

008: printf("Enter mass(kg): ");

009: scanf("%f", &mass);

010: printf("Enter height(m): ");

011: scanf("%f", &height);

012:

013: BMI = mass / (height * height);

014: printf("BMI (kilogram per square meter): %.2f ", BMI);

015:

016: return 0;

017: }

Note: In this example, I used a different source file as an input file. It meant to provide you with the format of the output file required to be generated by your program. In your project, the source file is the source file of the program that generates these line numbers.

Explanation / Answer

#include<stdio.h>

#include<string.h>

#define BUFFER 200

void main() {

   int lineCount = 0;

   FILE *fpIn = fopen(__FILE__,"r"); //macro ___FILE___ contains source file name

   char *fileOut = malloc(sizeof(char)*(strlen(__FILE__)+5)); // out file name

   strcpy(fileOut,__FILE__);

   strcat(fileOut,".txt");

   FILE *fpOut = fopen(fileOut,"w");

   char line[BUFFER]; //will hold each line

   if(fpIn == NULL){

      printf("Cannot read file ");

      return;

   }

   if(fpOut == NULL){

      printf("Cannot write file ");

      return;

   }

   while (fgets(line,BUFFER,fpIn) != NULL) { //read every line

      lineCount++; //increase line count

      fprintf(fpOut,"%03d: %s ",lineCount,line); //print them

   }

   fclose(fpOut);

   fclose(fpIn);

}

The code should work well if the executable file generated by the compiler is placed in the same directory as of the source code.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote