I have the following file as the input

APPLE 0 118 1 110 1 125 1 135 2 110 3 107 3 115 3 126
ORANGE 0 112 1 119 2 109 2 119 3 112 4 109 4 128
MANGO 0 136 1 143 2 143 3 143 4 136
BANANA 0 5 1 12 1 15 2 13 3 6 3 9

I need to read the above file and have the following information in the output file

In APPLE 0 occurs 1 time, 1 occurs 3 times, 2 occurs 1 time, 3 occurs 3 times
In ORANGE 0 occurs 1 time, 1 occurs 1 times, 2 occurs 2 time, 3 occurs 1 times, 4 occurs 2 times
In MANGO 0 occurs 1 time, 1 occurs 1 times, 2 occurs 1 time, 3 occurs 1 times, 4 occurs 1 times
In BANANA 0 occurs 1 time, 1 occurs 2 times, 2 occurs 1 time, 3 occurs 3 times

I started off with reading the input file, putting all the rows into an array. Now I am stuck at reading the row string from the array. Once I get the string, I want to parse the string and get the tokens. This is my idea. Do you have any suggestions to do this.

Following is the code I did to start with.

#include <stdio.h>
#include <stdlib.h>
#define FNAME "c:\\CProject\\input.txt"
#define OFNAME "c:\\CProject\\output.txt"
 
static FILE *fptr;
static FILE *fp ; 
 
void pause()
{
printf("\nProgram ended, Press ENTER: ");
fflush(stdin);
getchar();
}
 
void close_the_file()
{
close(fptr);
}
 
main()
{
char buffer[300];
int count = 0;
 
atexit(pause);
fptr = fopen(FNAME, "r"); //open the text file for reading
if (fptr == NULL)
{
perror("Could not open " FNAME);
exit(1);
}
atexit(close_the_file);
if((fp = fopen(OFNAME, "w"))==NULL) //Read all lines from the file
{
printf("Cannot open file.\n");
exit(1);
}
 
char lines[10000];
int j,k;
j=0; 
while (fgets(buffer, sizeof buffer, fptr) != NULL)
{
fflush(stdin);
// ++count; 
while(!feof(fptr))
{ // loop through and store the lines into the array 
fscanf(fptr, "%c", &lines[j]);
j++;
// fprintf(fp, "%c", lines[j]);
}
 
// ***** to do - read rows and then parse the row string ***** 
 
// printf("The lines are:\n",&lines[j]);
printf("Number of lines read: %d\n\n", j);
for(k=0 ; k<j ; k++)
{ 
fprintf(fp, "%c", lines[k]);
} 
} 
return 0;
}

The fflush on line 45 is non-standard and may cause undefined behavior. fflush() is for flushing output streams, not input streams.

Is that a C or a C++ program? If it is supposed to be C then rename the file to *.c instead of *.cpp and the compiler will treat it as C program. Then you will have to move lines 40 and 41 to the top of the function.

>>line 60 fprintf(fp, "%c", lines[k]);

Since variable lines is a simple char array why not teat it as one? fprintf(fp, "%s\n", lines);

This article has been dead for over six months. Start a new discussion instead.