I have a code here which needs to validate txt files and filter the data. I would need to use struct and realloc for my codes.
The idea here is to first read the txt file and store it in array. Then after that it will filter out the data based on the condition below. Those that meets the condition will go to data_1.txt and the others will go to error.txt.
I'm getting the error below for the struct which i'm not sure about it.
error C2440: '=' : cannot convert from 'void *' to 'Validation *'
Conversion from 'void*' to pointer to non-'void' requires an explicit cast
error C2062: type 'void' unexpected
error C2065: 'src' : undeclared identifier
error C2065: 'dest' : undeclared identifier
error C2065: 'type' : undeclared identifier
error C2065: 'port' : undeclared identifier
Sample source file:
9001:0002:9003:0021
0001:0010:0003:0021
8001:0002:8002:0080
Source Code:
#include <stdio.h>
#include <stdlib.h> //for exit (1)
#include <malloc.h>
struct Validation {
int src;
int dest;
int type;
int port;
char data[50];
};
int main ()
{
struct Validation *array;
int option;
FILE *inFile; //file handle or pointer
char filename[100];
char test;
int count = 0; //keep track number of records
int n1 = 0; //keep track number of correct records
int n2 = 0; //keep track number of error records
array = (struct Validation *) malloc (sizeof (struct Validation));
do {
printf ("Enter filename: ");
scanf ("%s", filename);
printf ("Processing filename %s ...\n", filename);
inFile = fopen (filename, "r");
if (inFile == NULL) //check if file handler is invalid
{
printf ("Could not open file %s\n", filename);
exit (1); //error status code
}
test = fscanf (inFile, "%d:%d:%d:%d:",
&array[count].src, array[count].dest,
array[count].type, array[count].port);
while (test != EOF) {
count++;
array = realloc (array, (count + 1) * sizeof (struct Validation));
test = fscanf (inFile, "%d:%d:%d:%d:",
&array[count].src, array[count].dest,
array[count].type, array[count].port);
}
}
void save (int, struct Validation *);
FILE *outFile;
FILE *errorFile;
int i;
outFile = fopen ("data_1.txt", "wt");
errorFile = fopen ("data_error.txt", "wt");
if (outFile == NULL) //check if file handler is invalid
{
printf ("Could not write to file \n", filename);
exit (1);
}
if (count > 0) {
printf ("Viewing all records: ", count);
for (i = 0; i < count;
i++, src >= 1 && src <= 1024 && dest >= 1 && dest <= 1024
&& type >= 1 && type <= 10 && port >= 1 && port <= 1024) {
fprintf (outFile, "%d %d %d %d",
(i + 1),
array[i].src,
array[i].dest,
array[i].type,
array[i].port);
n1++;
}
} else {
fprintf (errorFile, "%d %d %d %d",
array[i].src, array[i].dest, array[i].type, array[i].port);
n2++;
}
fclose (errorFile);
fclose (outFile);
fclose (inFile); //must always close file once done
free (array);
return 0;
}