0

created a struct which is shown below:

struct entry
{
    int source[5];
    int destination[5];
    int type[5];
    int port;
    int data;
} record;

user has to input a filename and the files need to be validated to a specific criteria and then stored but i'm nto sure how to use the malloc or calloc functions in my code to allow me to do this. Also need help with how to validate the text file. A snippet of code is shown below:

int file()
{   
    FILE *inFile;
    char inFileName[70]= {'\0'};
    char data1[70];
    char *token;

    int x = 0;
    int count = 0;
    int length = 0;

    printf("Enter File Name:");
    scanf("%s", inFileName);

    if ((inFile = fopen(inFileName, "r"))== NULL)
    {
        printf("Open failed:%s\n", inFileName);
        exit(1);
    }

    if (inFile != NULL)
    {
        while (!feof (inFile)) // Read the whole file until the end of the file.
        {
            count ++;
            printf("\n\nRecord:%i\n", count);
            fgets(data1, sizeof data1, inFile); //fgets reads the first string from the "inFile"        pointer and stores it in char "data" using the "sizeof" function to make sure strings are the same size.

            token = strtok(data1, ":"); // the "token" pointer used with the "strtok" function to break down the "data" string into smaller tokens by using the delimiter ":"
            record.source[5] = token;
            printf("Source:%d\n", record.source);
trooper
  • 4,444
  • 5
  • 32
  • 32

1 Answers1

1

You can use this to get the file size:

How do you determine the size of a file in C?

and then do a malloc of this size.

off_t size = fsize(inFileName);
char *data = malloc((size + 1) * sizeof(char));
off_t offset = 0;

and after fgets store the data like this:

fgets(data1, sizeof data1, inFile);
strcpy(data + offset, data1);
offset += strlen(data1);
Community
  • 1
  • 1
Telz
  • 116
  • 8
  • "undefined reference to fsize" is the error i'm getting back –  Dec 14 '14 at 17:07
  • You need to copy the function from the link I copied. You need to put it before your function file, or put "off_t fsize(char*);" before your function. You may need to include for the off_t type. – Telz Dec 14 '14 at 17:11