I have the following assignment in Intro to programming, we use codeblocks to pr
ID: 3904930 • Letter: I
Question
I have the following assignment in Intro to programming, we use codeblocks to program, so its programming in C.
Write a program to read the lines from file input.txt and follow the instructions below:
1- store the lines read into an array.
2- Print out the input of the array.
3- Write the lines into a file called output.txt per requirement below:
a) omit line 5 from the output file.
b) number each line in the output file.
The file input.txt, contains the follwing:
This is test line 1.
This is test line 2.
This is test line 3.
This is test line 4.
This is test line 5.
This is test line 6.
This is test line 7.
This is test line 8.
This is test line 9.
This is test line 10.
Thank you!
Explanation / Answer
Given below is the code for the question.
Please do rate the answer if it was helpful. Thank you
#include <stdio.h>
int main()
{
FILE *in, *out;
char infile[20] = "input.txt";
char outfile[20] = "output.txt";
char lines[100][256]; //100 lines eahc of length 256
int numLines = 0;
int i, j;
in = fopen(infile, "r");
if(in == NULL)
{
printf("ERROR: could not open input file %s for reading ", infile);
return 1;
}
out = fopen(outfile, "w");
if(out == NULL)
{
printf("ERROR: could not open input file %s for reading ", outfile);
return 1;
}
printf("Reading input file ");
fgets(lines[0], 256, in);
while(!feof(in))
{
numLines++;
fgets(lines[numLines], 256, in);
}
fclose(in);
printf("File %s has %d lines ", infile, numLines);
for(i = 0 ;i < numLines; i++)
puts(lines[i]);
printf(" Writing to output file %s ", outfile);
for(i = 0, j = 1; i < numLines; i++)
{
if(i == 4) //don't write 5th line
continue;
fprintf(out, "Line %d: %s", j, lines[i]);
j++;
}
fclose(out);
printf("Generated output in %s ", outfile);
}
output file generated: output.txt
===========
Line 1: This is test line 1.
Line 2: This is test line 2.
Line 3: This is test line 3.
Line 4: This is test line 4.
Line 5: This is test line 6.
Line 6: This is test line 7.
Line 7: This is test line 8.
Line 8: This is test line 9.
Line 9: This is test line 10.
output of program:
======
Reading input file
File input.txt has 10 lines
This is test line 1.
This is test line 2.
This is test line 3.
This is test line 4.
This is test line 5.
This is test line 6.
This is test line 7.
This is test line 8.
This is test line 9.
This is test line 10.
Writing to output file output.txt
Generated output in output.txt