Write A C program Objectives Working with files Reading from a file Writing to a
ID: 3912790 • Letter: W
Question
Write A C program
Objectives
Working with files
Reading from a file
Writing to a file
Scenario
Write a program that copies itself and adds line numbers to each line. You can (for now, to simplify your task, of course) assume
constant file names. First, open the file in read mode, then open the copy file in write mode. After that, line by line, get the lines from the source file, append the number of the line to the destination file, and append the line content. Remember to close both files. Note: in a real program, it's important to check whether all the needed files exist and that you can create a copy. In our program, you should at least check that both files have been successfully opened. If one of the fopen functions fails, then print the message: "Error opening a file." and end the program.
#include <stdio.h>
int main()
{
/* your code */
return 0;
}
Example output
Copy of source file with line numbers.
Explanation / Answer
#include <stdio.h>
#include <stdlib.h> // For exit()
const char EOL = ' '
int main()
{
FILE *fptr1, *fptr2;
char filename[100], c;
printf("Enter the filename to open for reading ");
scanf("%s", filename);
// Open one file for reading
fptr1 = fopen(filename, "r");
if (fptr1 == NULL)
{
printf("Cannot open file %s ", filename);
exit(0);
}
printf("Enter the filename to open for writing ");
scanf("%s", filename);
// Open another file for writing
fptr2 = fopen(filename, "w");
if (fptr2 == NULL)
{
printf("Cannot open file %s ", filename);
exit(0);
}
// Read contents from file
c = fgetc(fptr1);
int count = 0;
while (c != EOF)
{
count += 1;
fputc(count, fptr2)
while (c != EOL)
{
fputc(c, fptr2);
c = fgetc(fptr1);
}
}
printf(" Contents copied to %s", filename);
fclose(fptr1);
fclose(fptr2);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.