user3262678
user3262678

Reputation: 51

Struct Memory Allocation from File in C, only two variables work

I have to write a program that will read text from a file, break it up into a struct, validate the sections to a certain criteria, then produce two new files; one with the clean data and one with the errors. So far i am up to the stage of breaking up the data from a file and storing it into a struct but it will only work for the first two variables. the text is separated by colons and i need to put each section into the variables bellow an example of the text file

0001:0002:0003:0021:CLS

here is my struct

struct packet{
int source;
int destination;
int type;
int port;
char data[50];
};

Bellow is whatworks fine, however as soon as i add another section to add data to the type variable, the program does not work.

      fscanf(inFile, "%[^:]: %[^:]:", records[i].source, records[i].destination);
                        printf("%d - %s _ %s", i+1, records[i].source, records[i].destination);

However this does not work and i need it to. Well i need to expand upon it.

             fscanf(inFile, "%[^:]: %[^:]: %[^:]:", records[i].source, records[i].destination, records[i].type);
                        printf("%d - %s _ %s _ %s", i+1, records[i].source, records[i].destination, records[i].type);
                        }

if i printf without inputting anything to the struct it displays null as i would expect because nothing is being stored so im thinking that there is something wrong with the fscanf function. As it works for the first two, i dont think that it is a syntax issue so it must be a memory issue. I have used malloc and realloc but ive gotten confused with it and im sure that i have not done it right.

Full Code Listing

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

//declaration of function which will print my name and student number
const char * myname();
//declaration of a function that will prompt a user to enter a file and open it if it exists
int openfile();

struct packet{
    int source;
    int destination;
    int type;
    int port;
    char data[50];
    };


int main()
{
int recordCount = 0;

struct packet *records;
records =malloc(sizeof(struct packet));
// printing the my name and student number via the myname function
printf("%s\n", myname());
//executing the openfile function that will open a function
openfile(recordCount, records);


return 0;
}


const char * myname()
{
 const char *x = "*************************\nUSERNAME\nUSER NUMBER\nCONTACT NUMBER\n*************************\n";
 return x;
}


int openfile(int rCount, struct packet *records)
{
 //file pointer which will keep track of the file being accessed
FILE *inFile ;
//creating variable that will hold what the user has entered for a filename to open
char inFileName[100] = { '\0'};

printf("Please Enter the File to open:");
//getting the users input and storing it into the variable just created
scanf("%s", inFileName);
//if the file does not exist, display an appropriate error message
        if ((inFile = fopen(inFileName, "r")) == NULL)
        {
          printf("Cannot Open File **%s**\n", inFileName) ;
          exit(1) ;
        }

        else {
        //if the file does exist, process the data
            while(fgets(inFileName, 100, inFile)!=NULL)
                {


                int i =0;
                 for (i=0; i<30;i++)
                            {
                            fscanf(inFile, "%[^:]: %[^:]: %[^:]:", records[i].source, records[i].destination, records[i].type);
                            printf("%d - %s _ %s _ %s", i+1, records[i].source, records[i].destination, records[i].type);
                        }



                }

        //close the file
         fclose(inFile);
         return 0;
        }

};

Upvotes: 0

Views: 93

Answers (1)

unwind
unwind

Reputation: 399713

You're doing it wrong:

fscanf(inFile, "%[^:]: %[^:]:", records[i].source, records[i].destination);

The %[] conversion specifier is for string, but you're passing the values of integers as if they were character pointers. Undefined behavior!

You should be getting heaps of warnings for this from any modern compiler, i.e. one that validates formatting strings.

There's no point in parsing integers as if they were strings, I don't understand why you're not just doing

fscanf(inFile, "%d:%d", &records[i].source, &records.destination);

for the first case.

Also, do note that it's much better to read in whole lines using fgets(), then parsing the line once read using sscanf(), than trying to combine the two steps with fscanf().

Last, you should check the return value of the conversion call to know how many conversion succeeded.

Upvotes: 1

Related Questions