I am reading from a file "document" and printing it another file "docout". Additonally I would like to store each line in a char array and print it.
Consider the following code:
CODE
#include<stdio.h>
#define LINE_LENGTH 100
main()
{
/* All the declarations are here */
FILE *ifp, *ofp;
char *mode = "r";
int i,n1=0;
char c;
char line[LINE_LENGTH];
char sentence[6][LINE_LENGTH];
char outputFilename[] = "docout";
/* declaration ends */
ifp = fopen("document", mode);
if (ifp == NULL) {
fprintf(stderr, "Can't open input file text!\n");
exit(1);
}
/* Now counting the number of lines in a text document */
while ((c = getc(ifp)) != EOF)
if (c == '\n')
++n1;
printf("No. of lines = %d\n", n1);
ofp = fopen(outputFilename, "w");
if (ofp == NULL) {
fprintf(stderr, "Can't open output file %s!\n",
outputFilename);
exit(1);
}
i = 0;
while (NULL != fgets(line, LINE_LENGTH, ifp)){
sentence[i][LINE_LENGTH]=line[LINE_LENGTH];
i++;
fputs(line, ofp);
}
for (i=0; i < 6; i++) {
printf("Hello\n");
printf("%s%d\n", sentence[i][LINE_LENGTH],i);
}
fclose(ifp);
fclose(ofp);
}
[Document]
The old night keeper keeps the keep in the town.
In the big old house in the big old gown.
The house in the town had the big old keep.
Where the old night keeper never did sleep.
The old night keeper keeps the keep in the night.
And keeps in the dark and sleeps in the light.
[/Document]
I want the output to look like this:
sentence[0][LINE_LENGTH] = The old night keeper keeps the keep in the town.
sentence[1][LINE_LENGTH] = In the big old house in the big old gown.
etc.
Can you also give a more robust code using pointers?
regards,